在 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/