vue实现排序
实现数组排序
在Vue中实现数组排序可以通过计算属性或方法对数组进行处理。假设有一个数据列表需要根据特定条件排序:
data() {
return {
items: [
{ id: 1, name: 'Item C', price: 30 },
{ id: 2, name: 'Item A', price: 10 },
{ id: 3, name: 'Item B', price: 20 }
]
}
}
使用计算属性排序
创建计算属性返回排序后的数组,原数组保持不变:
computed: {
sortedItems() {
return [...this.items].sort((a, b) => a.price - b.price)
}
}
模板中直接使用sortedItems:
<ul>
<li v-for="item in sortedItems" :key="item.id">
{{ item.name }} - {{ item.price }}
</li>
</ul>
动态排序控制
添加排序控制参数实现动态排序方向切换:
data() {
return {
sortKey: 'price',
sortDirection: 1 // 1升序,-1降序
}
},
computed: {
sortedItems() {
return [...this.items].sort((a, b) => {
return (a[this.sortKey] > b[this.sortKey] ? 1 : -1) * this.sortDirection
})
}
}
添加排序控制按钮:
<button @click="sortDirection *= -1">切换排序方向</button>
多列排序
实现多字段排序逻辑,先按价格排序,价格相同再按名称排序:
computed: {
sortedItems() {
return [...this.items].sort((a, b) => {
if (a.price !== b.price) {
return (a.price - b.price) * this.sortDirection
}
return a.name.localeCompare(b.name) * this.sortDirection
})
}
}
表格列排序
在表格列头实现点击排序功能:
methods: {
sortBy(key) {
if (this.sortKey === key) {
this.sortDirection *= -1
} else {
this.sortKey = key
this.sortDirection = 1
}
}
}
表格模板示例:
<table>
<thead>
<tr>
<th @click="sortBy('name')">名称</th>
<th @click="sortBy('price')">价格</th>
</tr>
</thead>
<tbody>
<tr v-for="item in sortedItems" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.price }}</td>
</tr>
</tbody>
</table>
使用第三方库
对于复杂排序需求,可以使用lodash的orderBy函数:

import { orderBy } from 'lodash'
computed: {
sortedItems() {
return orderBy(
this.items,
[this.sortKey],
[this.sortDirection === 1 ? 'asc' : 'desc']
)
}
}






