- data 中提供数据,和搜索框双向绑定 (实时获取用户内容)
![image-20240211161725120](https://img-blog.csdnimg.cn/img_convert/a0a8d13a4d939587845362b7dbc88f33.png)
data () {
return {
search: ''
}
}
<van-search v-model="search" show-action placeholder="请输入搜索关键词" clearable>
<template #action>
<div>搜索</div>
</template>
</van-search>
- 准备假数据,进行基本的历史纪录渲染
data () {
return {
...
history: ['手机', '空调', '白酒', '电视']
}
},
<!-- 有历史记录才去做渲染 -->
<div class="search-history" v-if="history.length > 0">
<div class="title">
<span>最近搜索</span>
<van-icon @click="clear" name="delete-o" size="16" />
</div>
<div class="list">
<div v-for="item in history" :key="item" @click="goSearch(item)" class="list-item">
{{ item }}
</div>
</div>
</div>
- 点击搜索,或者下面搜索历史按钮,都要进行搜索历史记录更新 (去重,新搜索的内容置顶)
<div @click="goSearch(search)">搜索</div>
<div class="list">
<div v-for="item in history" :key="item" @click="goSearch(item)" class="list-item">
{{ item }}
</div>
</div>
<script>
methods: {
goSearch (key) {
const index = this.history.indexOf(key)
if (index !== -1) {
this.history.splice(index, 1)
}
this.history.unshift(key)
this.$router.push(`/searchlist?search=${key}`)
}
}
</script>
- 清空历史
<van-icon @click="clear" name="delete-o" size="16" />
clear () {
this.history = []
}