vue 实现数组排序
在 Vue 中实现数组排序的方法
使用 JavaScript 原生排序方法
Vue 中可以直接调用 JavaScript 的 Array.prototype.sort() 方法对数组进行排序。对于数字数组,需要传入比较函数:
data() {
return {
numbers: [3, 1, 4, 1, 5, 9, 2, 6]
}
},
methods: {
sortNumbers() {
this.numbers.sort((a, b) => a - b) // 升序
// this.numbers.sort((a, b) => b - a) // 降序
}
}
对于对象数组,可以指定排序依据的属性:
data() {
return {
items: [
{ name: 'Apple', price: 5 },
{ name: 'Orange', price: 3 },
{ name: 'Banana', price: 4 }
]
}
},
methods: {
sortByPrice() {
this.items.sort((a, b) => a.price - b.price)
}
}
使用计算属性实现排序
如果需要保持原始数据不变,可以使用计算属性返回排序后的数组:
computed: {
sortedItems() {
return [...this.items].sort((a, b) => a.price - b.price)
}
}
在模板中使用排序
可以直接在模板中使用计算属性或方法调用:
<ul>
<li v-for="item in sortedItems" :key="item.name">
{{ item.name }} - {{ item.price }}
</li>
</ul>
使用 Lodash 进行复杂排序
对于更复杂的排序需求,可以引入 Lodash 库:
import _ from 'lodash'
methods: {
sortByMultipleFields() {
this.items = _.orderBy(this.items, ['price', 'name'], ['asc', 'desc'])
}
}
响应式注意事项
Vue 无法检测到以下数组变动:
- 直接通过索引设置项:
this.items[index] = newValue - 直接修改数组长度:
this.items.length = newLength
要确保排序后的数组能被 Vue 检测到变化,应该:
- 使用变异方法(如
sort()) - 使用
this.$set()或Vue.set() - 返回新数组(如使用计算属性)
性能优化
对于大型数组,可以考虑:
- 使用 Web Worker 进行后台排序
- 实现虚拟滚动只渲染可见项
- 使用分页减少一次性渲染的数据量







