vue 实现数组排序
Vue 实现数组排序的方法
在 Vue 中实现数组排序可以通过多种方式完成,以下是几种常见的方法:
使用 JavaScript 原生方法
Vue 的响应式系统会自动追踪数组的变化,因此可以直接使用 JavaScript 的 sort() 方法对数组进行排序:

data() {
return {
items: [5, 3, 9, 1, 4]
}
},
methods: {
sortArray() {
this.items.sort((a, b) => a - b); // 升序排序
// this.items.sort((a, b) => b - a); // 降序排序
}
}
使用计算属性
如果需要保持原数组不变并返回排序后的新数组,可以使用计算属性:
data() {
return {
items: [5, 3, 9, 1, 4]
}
},
computed: {
sortedItems() {
return [...this.items].sort((a, b) => a - b);
}
}
在模板中直接排序
对于简单的排序需求,可以直接在模板中使用 sort() 方法:

<ul>
<li v-for="item in [...items].sort((a, b) => a - b)" :key="item">
{{ item }}
</li>
</ul>
对象数组排序
如果数组中的元素是对象,可以通过指定对象的属性进行排序:
data() {
return {
users: [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 20 }
]
}
},
methods: {
sortByAge() {
this.users.sort((a, b) => a.age - b.age);
}
}
使用 Lodash 库
对于更复杂的排序需求,可以使用 Lodash 的 orderBy 方法:
import _ from 'lodash';
data() {
return {
users: [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 20 }
]
}
},
computed: {
sortedUsers() {
return _.orderBy(this.users, ['age'], ['asc']);
}
}
注意事项
- Vue 无法检测到直接通过索引修改数组项的操作,例如
this.items[0] = newValue,应使用Vue.set或this.$set。 - 如果需要触发视图更新,应避免直接修改原数组,而是返回一个新数组。






