vuejs2之在 Vue.js 中对数组进行排序
mfryf
阅读:153
2025-06-02 22:19:02
评论:0
在 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.
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。



