element tree 深度查询

  searchTree () {
      this.keys = []
      this.filterLabel()
    },

    // 过滤标签树
    filterLabel (value, data) {
      // ''空字符串是查询全部
      if (this.searchLabel.trim() === '') {
        this.treeDataTemp = Array.from(this.treeData)
        this.keys = Array.from(this.defaultExpendKeys)
        this.$refs['left'].scrollTo({ y: 0 })
        return
      }
      let res = this.variableDeepSearch(this.treeData, this.searchLabel.trim()) // res是过滤后得到的数据

      let temp = [] // 存放包含关键字的标签  和  包含关键字的分类标签的父级key
      if (this.keys.length > 20) {
        this.$message.warning('匹配到的数据太多,请自行展开')
        this.keys = this.defaultExpendKeys // 太多直接是不展开
      } else {
        this.keys.forEach(item => {
          let node = this.$refs.tree.getNode(item)
          if (node.isLeaf) {
            temp.push(item) // 如果是叶子节点的话必须得展开
          } else {
            temp.push(node.parent.key) // 如果不是叶子节点那么展开它的父级
          }
        })
        this.keys = temp
      }
      this.treeDataTemp = Array.from(res)
      this.$refs['left'].scrollTo({ y: 0 }) // 搜索后滚动到顶部
    },

    // treeDataFilter标签树数据,searchWord搜素关键字
    variableDeepSearch (treeData, searchWord) {
      let childTemp = []

      treeData.forEach(element => {
        if (element.label.indexOf(searchWord) > -1) {
          childTemp.push(element)
          // 匹配到关键字并且key中还没存在他的父级
          if (!element.key.includes(this.keys[this.keys.length - 1])) {
            this.keys.push(element.key)
          }
        }
        if (element.children && element.children.length) {
          const childSearch = this.variableDeepSearch(element.children, searchWord)
          const childObj = {
            ...element,
            children: childSearch
          }
          if (childSearch && childSearch.length) {
            childTemp.push(childObj)
            let index = childTemp.indexOf(element)
            if (index > -1) {
              childTemp.splice(index, 1)
            }
          }
        }
      })
      return childTemp
    },

  

原文地址:https://www.cnblogs.com/ihuangqing/p/11588991.html