vue 实现排序
Vue 实现排序的方法
使用 Array.prototype.sort() 方法
Vue 中可以通过 JavaScript 原生的 sort() 方法对数组进行排序。在 Vue 的 data 或 computed 属性中定义数组,并在方法中调用 sort()。
data() {
return {
items: [5, 2, 9, 1, 3]
}
},
methods: {
sortItems() {
this.items.sort((a, b) => a - b); // 升序
// this.items.sort((a, b) => b - a); // 降序
}
}
使用计算属性实现动态排序
通过计算属性可以实时对数据进行排序,适合需要动态排序的场景。

data() {
return {
items: [5, 2, 9, 1, 3],
sortDirection: 'asc' // 'asc' 或 'desc'
}
},
computed: {
sortedItems() {
return [...this.items].sort((a, b) => {
return this.sortDirection === 'asc' ? a - b : b - a;
});
}
}
基于对象属性的排序
如果数组中的元素是对象,可以通过对象的某个属性进行排序。

data() {
return {
users: [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 20 }
],
sortBy: 'age', // 排序依据的属性
sortDirection: 'asc'
}
},
computed: {
sortedUsers() {
return [...this.users].sort((a, b) => {
const modifier = this.sortDirection === 'asc' ? 1 : -1;
return (a[this.sortBy] - b[this.sortBy]) * modifier;
});
}
}
使用 Lodash 库进行复杂排序
Lodash 提供了更强大的排序功能,适合处理复杂的数据结构或多条件排序。
import _ from 'lodash';
data() {
return {
users: [
{ name: 'Alice', age: 25, score: 80 },
{ name: 'Bob', age: 30, score: 90 },
{ name: 'Charlie', age: 20, score: 85 }
],
sortConfig: [
{ key: 'age', order: 'asc' },
{ key: 'score', order: 'desc' }
]
}
},
computed: {
sortedUsers() {
return _.orderBy(
this.users,
this.sortConfig.map(item => item.key),
this.sortConfig.map(item => item.order)
);
}
}
在表格中实现点击表头排序
结合 Vue 的模板和事件绑定,可以实现点击表头排序的功能。
<template>
<table>
<thead>
<tr>
<th @click="sortBy('name')">Name</th>
<th @click="sortBy('age')">Age</th>
</tr>
</thead>
<tbody>
<tr v-for="user in sortedUsers" :key="user.name">
<td>{{ user.name }}</td>
<td>{{ user.age }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
users: [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 20 }
],
sortKey: 'name',
sortDirection: 'asc'
}
},
computed: {
sortedUsers() {
return [...this.users].sort((a, b) => {
const modifier = this.sortDirection === 'asc' ? 1 : -1;
return a[this.sortKey] > b[this.sortKey] ? 1 * modifier : -1 * modifier;
});
}
},
methods: {
sortBy(key) {
if (this.sortKey === key) {
this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
} else {
this.sortKey = key;
this.sortDirection = 'asc';
}
}
}
}
</script>
注意事项
- 使用
sort()方法时,为了避免直接修改原始数组,建议先使用扩展运算符[...array]创建副本。 - 对于复杂的数据结构或多条件排序,Lodash 的
orderBy方法更为方便。 - 在表格中实现排序时,可以通过计算属性和事件绑定动态更新排序结果。






