我正在使用计算值来动态过滤数组(“订单”)。
计算的.filter()
函数允许用户按订单号,名称或参考号动态搜索:
data() {
return {
orders: [],
search: "" // search string from a text input
};
},
computed: {
filtered:
return this.orders.filter(order => {
const s =
order.order_number + order.reference + order.name;
const su = s.toUpperCase();
return su.match(this.search.toUpperCase());
});
}
我正在使用v-for
循环来呈现搜索结果,如下所示:
<tbody v-for="(order, index) in filtered" :key="order.id">
<tr>
<td @click="add_events(order, index)>{{order.order_number}}</td>
<td>{{order.reference}}</td>
<td>{{order.name}}</td>
...
</tr>
</tbody>
我想使用@click
来定位已过滤数组中的特定组件(对象),并使用$set
将该值(“ objEvents”)附加到该对象:
methods: {
add_events (order, index) {
const objEvents= [ external data from an API ]
this.$set(this.orders[index], "events", objEvents)
}
}
但是过滤的数组(“过滤的”)中组件的index
与原始中的组件index
不同数组(“订单”),因此add_events
方法定位的组件错误。
我可以使用key
定位正确的组件吗?还是有其他方法可以在过滤后的数组中标识目标组件?
答案 0 :(得分:2)
无需跟踪index
。 filtered
只是orders
中对原始对象的引用的数组,因此您可以修改order
中的add_events()
迭代器以实现所需的效果:
this.$set(order, 'events', objEvents);
new Vue({
el: '#app',
data() {
return {
orders: [
{id: 1, order_number: 111, name: 'John', reference: 'R111'},
{id: 2, order_number: 222, name: 'Bob', reference: 'R222'},
{id: 3, order_number: 333, name: 'Bob', reference: 'R333'},
],
search: ''
};
},
computed: {
filtered() {
return this.orders.filter(order => {
const s =
order.order_number + order.reference + order.name;
const su = s.toUpperCase();
return su.match(this.search.toUpperCase());
});
}
},
methods: {
add_events(order, index) {
const objEvents = [
{id: 1, name: 'Event 1'},
{id: 2, name: 'Event 2'},
{id: 3, name: 'Event 3'}
];
this.$set(order, "events", objEvents);
}
}
})
<script src="https://unpkg.com/vue@2.5.17"></script>
<div id="app">
<input type="text" v-model="search" placeholder="Search">
<table>
<tbody v-for="(order, index) in filtered" :key="order.id">
<tr>
<td @click="add_events(order, index)">{{order.order_number}}</td>
<td>{{order.reference}}</td>
<td>{{order.name}}</td>
<td>{{order.events}}</td>
</tr>
</tbody>
</table>
<pre>{{orders}}</pre>
</div>
答案 1 :(得分:1)
您可以映射原始数组,并将origIndex
属性添加到每个项目,如下所示:
computed:{
filtered(){
let mapped= this.orders.map((item,i)=>{
let tmp=item;
tmp.origIndex=i;
return tmp;
});
return this.mapped.filter(order => {
const s =
order.order_number + order.reference + order.name;
const su = s.toUpperCase();
return su.match(this.search.toUpperCase());
});
}
}//end computed
在模板中,使用origIndex
属性而不是index
<tbody v-for="(order, index) in filtered" :key="order.id">
<tr>
<td @click="add_events(order, order.origIndex)>{{order.order_number}}</td>
<td>{{order.reference}}</td>
<td>{{order.name}}</td>
...
</tr>
</tbody>