gpt4 book ai didi

filter - Vue.js filterBy 数组作为 searchText

转载 作者:搜寻专家 更新时间:2023-10-30 22:52:10 24 4
gpt4 key购买 nike

在 vue.js 中如何一个 filterBy 多个属性?

考虑以下数据结构。

new Vue({
el: body,
data: {
items: [
{name: 'thing1', age: 5, properties: [
{ name: 'color', value: 'black'},
{ name: 'weight', value: 3}
]},
{name: 'thing2', age: 3, properties: [
{ name: 'length', value: 4},
{ name: 'weight', value: 4}
]},
{name: 'thing3', age: 9, properties: [
{ name: 'color', value: 'black'},
{ name: 'length', value: 20}
]}
],
property: ''
}
});

现在,可以轻松地通过单个属性进行过滤,如下所示:

<input v-model="property" />
<div v-for="item in items | filterBy property in 'properties'">
{{ item.name }}
</div>

但是,如果我想通过多个属性进行搜索。
例如为了得到 thing3,我试过了,但是,当然,这行不通。

property: ['black', 20]

我需要实现某种动态 filterBy 链接吗?我不知道会有多少属性。

实现此目的的粗略方法是为当前项数组中的每个不同属性创建 filterBy,并将其中大部分保留为空。像这样。

new Vue({
el: body,
data: {
items: [],
property1: '',
property2: '',
property3: '',
...
propertyN: ''
}
});

还有这个:

<div v-for="item in items | filterBy property1 in 'properties'|
filterBy property2 in 'properties'|
filterBy property3 in 'properties'|
...
filterBy propertyN in 'properties'">
{{ item.name }}
</div>

但这样做感觉不对。

最佳答案

似乎自定义函数是唯一可行的选择。

filters: {
myProperty: function(items, properties = this.properties) {
if (!properties || properties.length === 0) {
return items;
}
return this.recursiveFilter(items, propeties, 0);
}
},
methods: {
recursiveFilter: function(items, properties, currentPosition) {
if (currentPosition+1 > properties.length)
return items;
var new_items;
new_items = items.filter(function(item) {
for (row of item.properties) {
if (row.value == properties[currentPosition])
return true;
}
});
return this.recursiveFilter(new_items, properties, currentPosition+1);
}
}

关于filter - Vue.js filterBy 数组作为 searchText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37431062/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com