我使用vue.js创建了过滤器部分。我通过ajax注入所有组件,它们动态响应这些过滤器。我的组件中的组件代表汽车,它们有价格,标记等......
现在我想添加两个过滤器,允许我按某个字段(例如价格)对它们进行排序。我一直在阅读,并且很容易对指定字段和订单的列表进行排序......
我应该如何继续创建该列表,以便能够对其进行排序。
Here我做了一个小小的小提琴,非常简单,我点击过滤器后我会按照奖品对汽车进行排序。
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){
}
}
});
答案 0 :(得分:1)
首先,将每个汽车组件的数据存储在父组件的数据属性中:
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
指令为box_car
数据属性中的每个对象创建cars
组件:
// 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);
}
}