小程序实现本地搜索

422 阅读1分钟

有时候后端他把数据丢给你,就靠你直接去本地做筛选,因为数据不是很多嘛,那么小程序本地怎么做筛选功能呢 因为渲染你只能用一个数据去渲染,所以如果你去把拿到的数据去筛选就会导致原数据被破坏,一开始有想过用深拷贝,可能是自己太菜,搞不定,所以我用的另一种方法,就是把数据本地备份一份 在请求拿到数据的时候备份一份

mzghxxcx(res.data.data).then(res => {//请求数据
          this.setData({
            mzghxxcx:res.dataJson,//备份一份作为筛选使用
            screening:res.dataJson
          })
         }

然后再点击搜索后

    let filter = []
    let val = this.data.value//搜索框的值
    let mzghxxcx = this.data.mzghxxcx//总数据
    let screening = this.data.screening//筛选备份数据
    if(mzghxxcx == [] || mzghxxcx == ""){//初始数据为空
        Toast.fail("查询结果失败");
        return mzghxxcx
    }else{
      console.log(this.data.value);
        if(this.data.value == "" || this.data.value == null){//输入框为空或者null赋值总数据
          this.setData({
            screening:mzghxxcx//备份的数据这时候就用上了
          })
        }else {
          screening.filter(its => {//在将得到的所有数据遍历
            if(its.NAME.indexOf(val) !== -1)  filter = [...filter,its]//数据中是否有搜索关键字,有则返回
          })
          this.setData({
            screening:filter//过滤后的数据
          })
        }
    }
  },
新建了个群,欢迎大家一起进群讨论459358760