html部分
<view class="inputBox">
<view class="input_box d-flex a-center">
<uni-icons type="search" size="20"></uni-icons>
<input class="flex-1" type="text" v-model="kw" placeholder="请输入搜索内容" @input="input" />
</view>
</view>
<!-- 搜索历史 -->
<view class="history-box" v-else>
<view class="history-title">
<text>搜索历史</text>
<uni-icons type="trash" size="17" @click="cleanHistory"></uni-icons>
</view>
<view class="history-list">
<uni-tag :text="item" v-for="(item, i) in historys" :key="i" @click="gotoGoodsList(item)"></uni-tag>
</view>
</view>
js部分
<script>
export default {
data() {
return {
timer: null,
kw: "",
searchResults: [],
historyList: []
}
},
onLoad() {
this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
},
computed: {
//将最新的搜索记录添加到数组开头
historys() {
return [...this.historyList].reverse()
}
},
methods: {
//搜索函数防抖
input(e) {
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.getSearchList()
}, 500)
},
//搜索
getSearchList() {
if (this.kw === '') {
this.searchResults = []
return
}
let obj = {
query: this.kw
}
this.$myApi.getSearchList(obj).then((res) => {
this.searchResults = res.data.message;
this.saveSearchHistory()
})
},
//保存搜索历史并持久化
saveSearchHistory() {
const set = new Set(this.historyList)
set.delete(this.kw)
set.add(this.kw)
this.historyList = Array.from(set)
uni.setStorageSync('kw', JSON.stringify(this.historyList))
},
// 清空搜索历史记录
cleanHistory() {
this.historyList = []
uni.setStorageSync('kw', '[]')
},
}
}
</script>