我尝试使用 slice().sort() 对 VueJS 2 中的项目列表进行排序,但它没有任何效果。在 vuejs 1 中有一个很好的 orderBy 过滤器,但他们删除了它。我当前的设置如下:
<table>
<thead>
<tr>
<th v-for="column in columns" v-on:click="sortBy(column)">{{ column }}</th>
</tr>
</thead>
<tbody>
<tr v-for="customer in customerslist">
<td>{{ customer.firstname }}</td>
<td>{{ customer.surname }}</td>
<td>{{ customer.added }}</td>
<td></td>
</tr>
</tbody>
</table>
...
sortBy(sortKey) {
this.customerslist = this.customerslist.slice().sort(sortKey);
console.log(sortKey);
console.log(this.customerslist[0].firstname);
}
这是一个包含客户的二维数组。每个客户都有名字、姓氏和添加的字段。
但是,如果我单击名字列标题,这总是会在控制台中返回相同的名字(尽管这不是按字母顺序排列的正确的名字)。排序是如何工作的,因为我找不到正确的文档。
最佳答案
你的问题与Vue没有任何关系。 JavaScript 中数组排序的工作方式与您的预期不同。您无法将键传递给 sort()
;相反,您必须实现自己的比较函数:
this.customerslist.sort((a, b) => a[sortKey].localeCompare(b[sortKey]));
排序也可以就地进行,因此不需要复制和重新分配数组。
关于javascript - VueJS 2 中的排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40405662/