gpt4 book ai didi

vuejs2 - 在 Vue.js 中对数组进行排序

转载 作者:行者123 更新时间:2023-12-01 22:53:06 25 4
gpt4 key购买 nike

在 v-for 循环中显示数组之前,如何按名称或性别对数组进行排序?
https://jsfiddle.net/rg50h7hx/

<div id="string">
<ul>
<li v-for="array in arrays">{{ array.name }}</li>
</ul>
</div>

// Vue.js v. 2.1.8
var string = new Vue({
el: '#string',
data: {
arrays: [
{ name: 'kano', sex: 'man' },
{ name: 'striker', sex: 'man' },
{ name: 'sonya', sex: 'woman' },
{ name: 'sindell', sex: 'woman' },
{ name: 'subzero', sex: 'man' }
]
}
})

我必须使用“计算”​​还是其他什么?

最佳答案

是的,一个简单的方法是创建一个可以返回 sortedArray 的计算属性,如下所示:

computed: {
sortedArray: function() {
function compare(a, b) {
if (a.name < b.name)
return -1;
if (a.name > b.name)
return 1;
return 0;
}

return this.arrays.sort(compare);
}
}

见工作 demo .

您可以找到排序文档 here它需要一个 compareFunction。

compareFunction Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.

关于vuejs2 - 在 Vue.js 中对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42883835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com