js 模糊搜索树形结构数据


 

<template>
  <div class="content">
    <search @getValue="getValue" />
  </div>
</template>
<script>
export default {
  name: "selectTree",
  data() {
    return {
      treeListTmp: [],
      treeList: [
        {
          name: "飞机1",
          hasChild: true,
          id: 1,
          children: [
            {
              name: "数据1-1",
              hasChild: true,
              id: 2,
              children: [
                {
                  name: "数据1-1-1",
                  hasChild: false,
                  id: 3,
                },
              ],
            },
            {
              name: "火箭1-2",
              hasChild: false,
              id: 4,
            },
          ],
        },
        {
          name: "数据2",
          hasChild: true,
          id: 5,
          children: [
            {
              name: "轮船2-1",
              hasChild: true,
              id: 6,
              children: [
                {
                  name: "数据2-1-1",
                  hasChild: false,
                  id: 7,
                },
              ],
            },
            {
              name: "数据2-2",
              hasChild: false,
              id: 8,
            },
          ],
        },
      ],
    };
  },
  created() {},
  methods: {
    getValue(msg) {
      this.treeList = [];
      let treeListTmp = JSON.parse(JSON.stringify(this.treeListTmp));
      let tmp = msg
        ? this.rebuildData(msg, treeListTmp)
        : JSON.parse(JSON.stringify(treeListTmp));
      this.treeList.push(...tmp);
    },
    rebuildData(value, arr) { if (!arr) { return []; } let newarr = []; if (Object.prototype.toString.call(arr) === "[object Array]") { arr.forEach((element) => { if (element.name.indexOf(value) > -1) { const ab = this.rebuildData(value, element.children); const obj = { ...element, children: ab, }; newarr.push(obj); } else { if (element.children && element.children.length > 0) { const ab = this.rebuildData(value, element.children); const obj = { ...element, children: ab, }; if (ab && ab.length > 0) { newarr.push(obj); } } } }); } return newarr; },
  },
};
</script>

 

参考地址:https://blog.csdn.net/web_yueqiang/article/details/89483971


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM