vue 实现排序
Vue 实现排序的方法
使用计算属性排序
在Vue中可以通过计算属性对数组进行排序。计算属性会基于依赖的响应式数据自动更新。
data() {
return {
items: [
{ name: 'Apple', price: 10 },
{ name: 'Banana', price: 5 },
{ name: 'Orange', price: 8 }
],
sortKey: 'price',
sortOrder: 1 // 1为升序,-1为降序
}
},
computed: {
sortedItems() {
return [...this.items].sort((a, b) => {
return (a[this.sortKey] > b[this.sortKey] ? 1 : -1) * this.sortOrder
})
}
}
使用方法触发排序
可以通过方法动态改变排序条件和顺序。

methods: {
sortBy(key) {
if (this.sortKey === key) {
this.sortOrder *= -1
} else {
this.sortKey = key
this.sortOrder = 1
}
}
}
使用v-for渲染排序结果
在模板中使用计算属性渲染已排序的数据。
<table>
<thead>
<tr>
<th @click="sortBy('name')">Name</th>
<th @click="sortBy('price')">Price</th>
</tr>
</thead>
<tbody>
<tr v-for="item in sortedItems" :key="item.name">
<td>{{ item.name }}</td>
<td>{{ item.price }}</td>
</tr>
</tbody>
</table>
使用lodash进行复杂排序
对于更复杂的排序需求,可以使用lodash的排序函数。

import _ from 'lodash'
computed: {
sortedItems() {
return _.orderBy(
this.items,
[this.sortKey],
[this.sortOrder > 0 ? 'asc' : 'desc']
)
}
}
对象数组的多条件排序
实现多字段排序时,可以扩展排序逻辑。
computed: {
sortedItems() {
return [...this.items].sort((a, b) => {
if (a.price !== b.price) {
return (a.price > b.price ? 1 : -1) * this.sortOrder
}
return (a.name > b.name ? 1 : -1) * this.sortOrder
})
}
}
使用Vuex管理排序状态
在大型应用中,可以使用Vuex集中管理排序状态。
// store.js
state: {
sortOptions: {
key: 'price',
order: 'asc'
}
},
mutations: {
updateSort(state, payload) {
state.sortOptions = payload
}
}






