filter - Vue.js filterBy 数组作为 searchText

标签 filter vue.js

在 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/

相关文章:

filter - 分组后如何按父值过滤结果?

awk - 使用 awk 过滤文件并在输出中保留标题

elasticsearch - 在Logstash中过滤jdbc数据

Excel:删除一列中的重复项,同时保留相邻列中的最高值

javascript - Vue.js mixin 引入本地状态

vue.js - 在 vuejs 中传递值?

mongodb - 获取 MongoDB 文档 WHERE 状态和日期之间

vue.js - Vue.use 和使用 VueRouter 导入构造函数之间的区别

php - Laravel 5.1 + Vue.js - vue-router beforeEach AuthService

javascript - 将 prop 从父组件传递到子组件时出错