uni-app搜索历史记录功能实现

发表于

searchStart: function () {
  let _this = this;
  if (_this.searchText == '') {//搜索关键词为空
    uni.showToast({//提示信息
      title: '请输入关键字',
      icon: 'none',
      duration: 1000
    });
  } else {
    uni.getStorage({//从缓存中取搜索历史记录的数组
      key: 'search_cache',
      success(res) {//获取成功
        let list = res.data;
        for (let i in list) {//循环遍历
          if (list[i] == _this.searchText) {//如果缓存数组中有搜索关键词
            list.splice(i, 1)//删除数组中的该关键词
          }
        }
        list.unshift(_this.searchText);//将搜索关键词添加到数组开头
        list.splice(6)//只保留6个
        _this.hList = list;
        uni.setStorage({//将新的数组存入缓存
          key: 'search_cache',
          data: _this.hList,
        });
        _this.search(_this.searchText);//搜索
      },
      fail() {//没有获取到缓存
        _this.hList = [];
        _this.hList.push(_this.searchText);
        uni.setStorage({
          key: 'search_cache',
          data: _this.hList,
        });
        _this.search(_this.searchText);//搜索
      }
    })
  }
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注