二级菜单实现模糊搜索

实现二级菜单下有很多数据,但只搜索出符合条件的

数据格式如下

this.data = [
          {
            name: '张三',
            id: '123',
            tag: [
              {
                id: 'a1',
                name: '标签名',
              },
              {
                id: 'a1',
                name: '套餐',
              },
            ],
          },
          {
            name: '李四',
            id: '456',
            tag: [
              {
                id: 'b1',
                name: '标签',
              },
              {
                id: 'b2',
                name: '数字',
              },
            ],
          },
        ]

 

查看代码
onSearch() {
      if (this.searchValue) {  //输入框的值
        let text = this.searchValue
        let reg = new RegExp(text)
        //利用正则规则获取符合搜索条件的数据
        let list = []  //用来保存最后的过滤出来的数据
        this.data = [] 
        let dataArr = JSON.parse(JSON.stringify(this.allData)) //备份一下原数据


        dataArr.forEach((item) => {  //遍历一级菜单
          let arr = []  //用来保存满足条件的二级菜单
          item.tag.map((i) => {  //遍历一级菜单里面的二级菜单tag
            if (reg.test(i.name)) {  //如果有满足的条件二级菜单的就保存
              arr.push(i)
            }
          })
          if (arr.length > 0) { 
            let listArr = item //如果有满足的arr的就把当时它的父菜单拿出来
            listArr.tag = arr //然后替换一下原来的tag
            list.push(listArr) //最后保存好,这个就是我们最后展示的数据
          }
        })
        //获取符合条件的数据
        this.data = list


      } else {
        //searchValue为空,则恢复全部数据显示
        this.data = this.allData
      }
    },

实现效果

实现前

   

实现后

posted @ 2022-11-17 16:41  Private!  阅读(97)  评论(0编辑  收藏  举报