0
0
Fork 0

feat(VnSelect): order data equal salix

This commit is contained in:
Alex Moreno 2024-11-12 14:35:55 +01:00
parent 86b8f9bf54
commit 3f15c3cce0
2 changed files with 56 additions and 0 deletions

View File

@ -3,6 +3,8 @@ import { ref, toRefs, computed, watch, onMounted, useAttrs } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import FetchData from 'src/components/FetchData.vue'; import FetchData from 'src/components/FetchData.vue';
import { useRequired } from 'src/composables/useRequired'; import { useRequired } from 'src/composables/useRequired';
import dataByOrder from 'src/utils/dataByOrder';
const emit = defineEmits(['update:modelValue', 'update:options', 'remove']); const emit = defineEmits(['update:modelValue', 'update:options', 'remove']);
const $attrs = useAttrs(); const $attrs = useAttrs();
const { t } = useI18n(); const { t } = useI18n();
@ -138,6 +140,7 @@ function findKeyInOptions() {
} }
function setOptions(data) { function setOptions(data) {
data = dataByOrder(data, $props.sortBy);
myOptions.value = JSON.parse(JSON.stringify(data)); myOptions.value = JSON.parse(JSON.stringify(data));
myOptionsOriginal.value = JSON.parse(JSON.stringify(data)); myOptionsOriginal.value = JSON.parse(JSON.stringify(data));
emit('update:options', data); emit('update:options', data);

53
src/utils/dataByOrder.js Normal file
View File

@ -0,0 +1,53 @@
function orderData(data, order) {
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));
} else if (typeof order === 'function') return data.sort(data);
return data;
}
function sortFunc(a, b, order) {
for (let i of order) {
let compRes = compareFunc(a[i.field], b[i.field]) * i.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;