1. data中新建一个数据用来存储搜索历史
data() {
return {
historyList: [], // 存储搜索历史的数据
kw: '', // 存储输入框的值
};
},
2. 在输入框输入内容调用接口获取数据之后把输入的内容存到 historyList
async getSearchList(){
// 判断输入框是否为空
if(!this.kw){
return this.searchResults = []
}
const {message:res} = await api.getData("/goods/qsearch", {query: this.kw})
// console.log(res)
this.searchResults = res
this.saveSearchHistory() // 存储历史记录的方法
},
saveSearchHistory(){
// 创建 set 实例
const set = new Set(this.historyList)
// 调用 set 的 delete 删除方法 和 add 添加方法
// 先删除输入的内容 然后在末尾添加
set.delete(this.kw)
set.add(this.kw)
// 将 set 转换为 数组形式 进行储存
this.historyList = Array.from(set)
// console.log(set)
// 顺便进行本地持久化的存储
uni.setStorageSync('kw', JSON.stringify(this.historyList))
},
3. 利用计算属性对 historyList 进行翻转
computed:{
// 页面上循环遍历展示的就是这个 histories 了
// 而不是 data 内存的 historyList
histories(){
//注意这里不要对原有的 historyList 数组进行 翻转
return [...this.historyList].reverse()
}
}
4. 因为进行了本地储存 所以可以在一开始加载页面的时候 给 historyList 赋值本地数据
onLoad() {
this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
},
5. 清除搜索历史
clearHistory(){
this.historyList = []
uni.setStorageSync('kw', '[]')
}
6. 完整代码:
注意:不能直接赋值粘贴,只是为了怕有些小伙伴看前面的代码段云里雾里的就给大家看一下完整代码作为参考O(∩_∩)O~
<template>
<view>
<view class="search-box">
<!-- 监听 input 事件 -->
<uni-search-bar :focus="true" @input="input" :radius="100" :cancelButton="none"></uni-search-bar>
</view>
<view class="sugg-list" v-if="searchResults.length !== 0">
<view @click="gotoDetail(item)" class="sugg-item" v-for="(item, i) in searchResults" :key="i">
<view class="goods-name">{{item.goods_name}}</view>
<uni-icons type="arrowright" size="16"></uni-icons>
</view>
</view>
<view class="history-box" v-else>
<view class="history-title">
<text>搜索历史</text>
<uni-icons @click="clearHistory" type="trash" size="17"></uni-icons>
</view>
<view class="histroy-list">
<uni-tag :text="item" v-for="(item, i) in histories" :key="i"></uni-tag>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
kw: '',
historyList: []
};
},
onLoad() {
this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
},
methods:{
async getSearchList(){
// 判断输入框是否为空
if(!this.kw){
return this.searchResults = []
}
const {message:res} = await api.getData("/goods/qsearch", {query: this.kw})
// console.log(res)
this.searchResults = res
this.saveSearchHistory()
},
saveSearchHistory(){
// this.historyList.push(this.kw)
const set = new Set(this.historyList)
set.delete(this.kw)
set.add(this.kw)
this.historyList = Array.from(set)
// console.log(set)
uni.setStorageSync('kw', JSON.stringify(this.historyList))
},
clearHistory(){
this.historyList = []
uni.setStorageSync('kw', '[]')
}
},
computed:{
histories(){
return [...this.historyList].reverse()
}
}
}
</script>
<style lang="scss">
</style>