如何在Vue.js 3中对数组进行排序?

huangapple go评论42阅读模式
英文:

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 : &#39;name&#39;, age :20},
  {name : &#39;name&#39;, age :21},
  {name : &#39;name&#39;, age :2},
]);

const sorted = computed(() =&gt; list.slice().sort((a, b) =&gt; a.name.localeCompare(b.name)));

list.push({name: &#39;name&#39;, age: 30});
// sorted will be updated on the next tick

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月25日 23:45:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76334120.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定