method one:
// 保存搜索关键词为历史记录
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))
}
Solve the problem of the sequence of keywords before and after:
computed: {
historys() {
// 注意:由于数组是引用类型,所以不要直接基于原数组调用 reverse 方法,以免修改原数组中元素的顺序
// 而是应该新建一个内存无关的数组,再进行 reverse 反转
return [...this.historyList].reverse()
}
}
When rendering the search keyword on the page, instead of using the data historyList
, use the calculated property historys
:
<view class="history-list">
<uni-tag :text="item" v-for="(item, i) in historys" :key="i"></uni-tag>
</view>
Method 2: It not only solves the problem of the sequence of keywords, but also solves the problem of deduplication of keywords
saveSearchHistory(value){
// 将搜索关键字保存到历史记录
this.historyList.unshift(value)
// 关键字去重
this.historyList=Array.from(new Set(this.historyList))
// 并且保存到本地存储
uni.setStorageSync('HistorySearch',JSON.stringify(this.historyList))
},