vue2.0 实现orderby
Vue 2.0 实现 OrderBy 功能
在 Vue 2.0 中,可以通过计算属性或方法对数据进行排序。以下是几种常见的实现方式:
使用计算属性实现排序
通过计算属性对数组进行排序是最直接的方式,可以结合 sort 方法实现升序或降序排列。

new Vue({
data() {
return {
items: [
{ name: 'Item C', price: 30 },
{ name: 'Item A', price: 10 },
{ name: 'Item B', price: 20 }
],
sortKey: 'name',
sortOrder: 1 // 1 for ascending, -1 for descending
}
},
computed: {
sortedItems() {
return [...this.items].sort((a, b) => {
if (a[this.sortKey] < b[this.sortKey]) return -1 * this.sortOrder
if (a[this.sortKey] > b[this.sortKey]) return 1 * this.sortOrder
return 0
})
}
}
})
使用过滤器实现排序
Vue 2.0 支持过滤器,可以通过过滤器对数据进行排序。但过滤器在 Vue 3.0 中已被移除,不推荐在新项目中使用。
Vue.filter('orderBy', function (array, key, order) {
return array.slice().sort((a, b) => {
if (a[key] < b[key]) return -1 * order
if (a[key] > b[key]) return 1 * order
return 0
})
})
动态切换排序字段和顺序
可以通过方法动态切换排序的字段和顺序,结合按钮或下拉菜单触发排序。

methods: {
sortBy(key) {
if (this.sortKey === key) {
this.sortOrder *= -1
} else {
this.sortKey = key
this.sortOrder = 1
}
}
}
多字段排序
对于需要按多个字段排序的情况,可以在排序函数中添加额外的判断逻辑。
computed: {
sortedItems() {
return [...this.items].sort((a, b) => {
if (a.field1 !== b.field1) {
return (a.field1 < b.field1 ? -1 : 1) * this.sortOrder
}
return (a.field2 < b.field2 ? -1 : 1) * this.sortOrder
})
}
}
使用 Lodash 实现复杂排序
对于更复杂的排序需求,可以引入 Lodash 的 orderBy 方法。
import _ from 'lodash'
computed: {
sortedItems() {
return _.orderBy(
this.items,
[this.sortKey],
[this.sortOrder === 1 ? 'asc' : 'desc']
)
}
}
以上方法可以根据具体需求选择使用。计算属性方式最为推荐,因其响应式特性能够自动更新视图。
