英文:
How to sort an array in Vue.js 3?
问题
I have an array of objects
let list = reactive([
{ name: 'name', age: 20 },
{ name: 'name', age: 21 },
{ name: 'name', age: 2 },
]);
and using v-for, I am displaying the values of the object.
What I want to achieve is to sort the array on button click, and return the sorted array.
While sorting works, sorted value is not displayed in the front-end, and my guess is I am misunderstanding something in the reactivity of Vue 3.
P.S
The sorted array should not be computed property, as I need to dynamically add/remove the objects from it.
Thanks
英文:
I have an array of objects
let list = reactive([
{name : 'name', age :20},
{name : 'name', age :21},
{name : 'name', age :2},
]);
and using v-for, I am displaying the values of the object.
What I want to achieve is to sort the array on button click, and return the sorted array.
While sorting works, sorted value is not displayed in the front-end, and my guess is I am misunderstanding something in the reactivity of Vue 3.
P.S
The sorted array should not be computed property, as I need to dynamically add/remove the objects from it.
Thanks
答案1
得分: 0
你应该仍然使用一个已排序的 computed
。只需向原始数组添加/删除值,你的 computed
会自动反映这些变化。
const list = reactive([
{name: 'name', age: 20},
{name: 'name', age: 21},
{name: 'name', age: 2},
]);
const sorted = computed(() => list.slice().sort((a, b) => a.name.localeCompare(b.name)));
list.push({name: 'name', age: 30});
// 排序将在下一个时钟周期更新
英文:
Still you should use a sorted computed
. Just add/remove values to/from original array, and your computed
reactively reflect those changes.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const list = reactive([
{name : 'name', age :20},
{name : 'name', age :21},
{name : 'name', age :2},
]);
const sorted = computed(() => list.slice().sort((a, b) => a.name.localeCompare(b.name)));
list.push({name: 'name', age: 30});
// sorted will be updated on the next tick
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论