vuejs3

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.

Note: the sorted array should not be a computed property, as I need to dynamically add/remove the objects from it.


Solution

  • Still you should use a sorted computed. Just add/remove values to/from original array, and your computed would reactively reflect those changes.

    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