diff --git a/src/components/common/VnSelect.vue b/src/components/common/VnSelect.vue index 32dbbd641..4622f1cb0 100644 --- a/src/components/common/VnSelect.vue +++ b/src/components/common/VnSelect.vue @@ -3,6 +3,8 @@ import { ref, toRefs, computed, watch, onMounted, useAttrs } from 'vue'; import { useI18n } from 'vue-i18n'; import FetchData from 'src/components/FetchData.vue'; import { useRequired } from 'src/composables/useRequired'; +import dataByOrder from 'src/utils/dataByOrder'; + const emit = defineEmits(['update:modelValue', 'update:options', 'remove']); const $attrs = useAttrs(); const { t } = useI18n(); @@ -138,6 +140,7 @@ function findKeyInOptions() { } function setOptions(data) { + data = dataByOrder(data, $props.sortBy); myOptions.value = JSON.parse(JSON.stringify(data)); myOptionsOriginal.value = JSON.parse(JSON.stringify(data)); emit('update:options', data); diff --git a/src/utils/dataByOrder.js b/src/utils/dataByOrder.js new file mode 100644 index 000000000..1bdedb8a1 --- /dev/null +++ b/src/utils/dataByOrder.js @@ -0,0 +1,54 @@ +function orderData(data, order) { + if (typeof order === 'function') return data.sort(data); + if (typeof order === 'string') order = [order]; + if (Array.isArray(order)) { + let orderComp = []; + + for (let field of order) { + let split = field.split(/\s+/); + orderComp.push({ + field: split[0], + way: split[1] === 'DESC' ? -1 : 1, + }); + } + + return data.sort((a, b) => sortFunc(a, b, orderComp)); + } + return data; +} + +function sortFunc(a, b, order) { + for (let { field, way } of order) { + let compRes = compareFunc(a[field], b[field]) * way; + if (compRes !== 0) return compRes; + } + + return 0; +} + +function compareFunc(a, b) { + if (a === b) return 0; + let aType = typeof a; + if (aType === typeof b) { + switch (aType) { + case 'string': + return a.localeCompare(b); + case 'number': + return a - b; + case 'boolean': + return a ? 1 : -1; + case 'object': + if (a instanceof Date && b instanceof Date) + return a.getTime() - b.getTime(); + } + } + + if (a === undefined) return -1; + if (b === undefined) return 1; + if (a === null) return -1; + if (b === null) return 1; + + return a > b ? 1 : -1; +} + +export default orderData;