我使用 vue.js 制作了过滤器部分。我通过 ajax 注入(inject)所有组件,它们动态响应这些过滤器。在我的例子中,组件代表汽车,它们有价格、标记等......
现在我想再添加两个过滤器,以便我可以按某个字段(例如价格)对它们进行排序。我一直在阅读,对指定字段和顺序的列表进行排序非常容易......
我应该如何继续创建该列表,以便能够对其进行排序。
Here我做了一个小 fiddle ,非常简单,一旦我点击过滤器,我就会按奖品对汽车进行排序。
var Car = Vue.extend({
template: '#template_box_car',
props: {
show: {
default: true
},
code: {
default: ""
},
prize: {
default: 0
},
description: {
default: "No comment"
}
}
});
//register component
Vue.component('box_car',Car);
//create a root instance
var vm = new Vue({
el: 'body',
methods: {
sortBy: function(field, order){
}
}
});
最佳答案
首先,将每个汽车组件的数据存储在父组件的数据属性中:
data: function () {
return {
cars: [
{ code: '11A', prize: 5.00, description: 'Ford Ka' },
{ code: '11B', prize: 3.00, description: 'Kia ceed' },
{ code: '11C', prize: 6.00, description: 'Ford Ka' },
{ code: '13A', prize: 45.00, description: 'Mercedes A' },
{ code: '17B', prize: 20.00, description: 'Seat Leon' },
]
}
},
然后,使用 v-for
指令为 cars
数据属性中的每个对象创建一个 box_car
组件:
// In your version of Vue.js it would look like this:
<box_car
v-for="car in cars"
:code="car.code"
:prize="car.prize"
:description="car.description"
:track-by="code"
></box_car>
// In newer versions of Vue.js, you can pass each object to the `v-bind` directive
// so you don't need to explicitly set each property:
<box_car v-for="car in cars" v-bind="car" :key="car.code"></box_car>
然后,在您的 sortBy
方法中,只需对 cars
数组进行排序即可:
// I used lodash, but you can sort it however you want:
methods: {
sortBy: function(field, order) {
this.cars = _.orderBy(this.cars, field, order);
}
}
关于javascript - 可排序的组件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44113301/