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