使用 Set 对象对关键字进行去重操作

方法一: 

// 保存搜索关键词为历史记录
saveSearchHistory() {
  // this.historyList.push(this.kw)

  // 1. 将 Array 数组转化为 Set 对象
  const set = new Set(this.historyList)
  // 2. 调用 Set 对象的 delete 方法,移除对应的元素
  set.delete(this.kw)
  // 3. 调用 Set 对象的 add 方法,向 Set 中添加元素
  set.add(this.kw)
  // 4. 将 Set 对象转化为 Array 数组
  this.historyList = Array.from(set)
 // 调用 uni.setStorageSync(key, value) 将搜索历史记录持久化存储到本地
  uni.setStorageSync('kw', JSON.stringify(this.historyList))
}

会关键字前后顺序的问题,解决:

computed: {
  historys() {
    // 注意:由于数组是引用类型,所以不要直接基于原数组调用 reverse 方法,以免修改原数组中元素的顺序
    // 而是应该新建一个内存无关的数组,再进行 reverse 反转
    return [...this.historyList].reverse()
  }
}

页面中渲染搜索关键词的时候,不再使用 data 中的 historyList,而是使用计算属性 historys

<view class="history-list">
  <uni-tag :text="item" v-for="(item, i) in historys" :key="i"></uni-tag>
</view>

 方法二:即解决了关键字前后顺序的问题,又解决了关键字去重

 saveSearchHistory(value){
        // 将搜索关键字保存到历史记录
        this.historyList.unshift(value)
        // 关键字去重
        this.historyList=Array.from(new Set(this.historyList))
        // 并且保存到本地存储
        uni.setStorageSync('HistorySearch',JSON.stringify(this.historyList))
      },

猜你喜欢

转载自blog.csdn.net/m0_65812066/article/details/129218224
今日推荐