过滤嵌套(递归)数据(Vue 2)

时间:2019-03-05 14:47:19

标签: vue.js filter nested lodash children

这是我的JSON数据的示例:

"data":[  
  {  
     "id":01,
     "name":"test",
     "parent_id":null,
     "children":[  
        {  
           "id":15,
           "name":"subChild",
           "parent_id":21,
           "children":[  
              {  
                 "id":148,
                 "name":"subSubChild",
                 "parent_id":22,
                 "children":[  
                        ....
                 ]
              }
           ]
        }
     ]
  },

我想逐级过滤该级别。我已经做了这个方法:

computed: {
      filteredData: function () {
        let filterData = this.filter.toLowerCase()
        return _.pickBy(this.data, (value, key) => {
          return _.startsWith(value.name.toLowerCase(), filterData)
        })
      },

这项功能仅适用于第一个“级别”,我尝试了几种解决方案,但没有一种适用于儿童。

因此,我希望能够按几个级别进行过滤。

如果您有想法! 谢谢

1 个答案:

答案 0 :(得分:1)

为此特定目的,递归函数可能会派上用场。

请尝试以下方法,为了获得更好的视图,请点击下方运行代码段按钮旁边的Full page链接。

new Vue({
  el: '#app',

  data() {
    return {
      filter: '',
      maintainStructure: false,
      data: [{
        "id": 01,
        "name": "test",
        "parent_id": null,
        "children": [{
          "id": 15,
          "name": "subChild",
          "parent_id": 21,
          "children": [
            {
              "id": 148,
              "name": "subSubChild",
              "parent_id": 22,
              "children": []
            }, 
            {
              "id": 150,
              "name": "subSubChild3",
              "parent_id": 24,
              "children": []
            }
          ]
        }]
      }]
    }
  },

  methods: {
    $_find(items, predicate) {
      let matches = [];

      for (let item of items) {
        if (predicate(item)) {
          matches.push(item);
        } 
        else if (item.children.length) {
          let subMatches = this.$_find(item.children, predicate);
          
          if (subMatches.length) {
            if (this.maintainStructure) {
              matches.push({
                ...item,
                children: subMatches
              });
            }
            else {
              matches.push(subMatches);
            }
          }
        }
      }

      return matches;
    },

    filterBy(item) {
      return item.name.toLowerCase().startsWith(this.filter.toLowerCase());
    }
  },

  computed: {
    filteredData() {
      return this.$_find(this.data, this.filterBy);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div>
    <label>Filter by <code>item.name</code>:</label>
    <input v-model.trim="filter" placeholder="e.g. subsub" />
  </div>
  
  <div>
    <label>
      <input type="checkbox" v-model="maintainStructure" /> Maintain structure
    </label>
  </div>
  
  <hr />
  
  <pre>{{filteredData}}</pre>
</div>

请注意,我要在函数前加上$_,以将其标记为 private 函数(如this Style Guide中的建议),因为我们不会调用在其他任何地方。