效果图
代码html部分
<div class="sear_header">
<img @click="$router.back()" src="@/assets/back.png" alt="">
<div class="search">
<van-search v-model="value" show-action placeholder="搜索" @search="onSearch">
<template #action>
<div @click="onSearch">搜索</div>
</template>
</van-search>
</div>
</div>
<div class="sear_histor">
<div class="history">
<div class="title">
<p>最近搜索</p>
<img @click="del" src="@/assets/sear_del.png" alt="">
</div>
<div class="content">
<span v-if="!historyList.length">暂无</span>
<!-- 采用本地存储 -->
<span v-else @click="value=item;onSearch()" v-for="(item,index) in historyList"
:key="index">{{item}}</span>
</div>
</div>
vue data 数据
data() {
return {
value: '',
historyList: [],
hot: ["防晒", '精华', '面霜', '粉底', '眼影'],
}
},
vue 一些事件
页面挂载完毕判断本地存储是否有数据
mounted() {
if (JSON.parse(localStorage.getItem('history'))) {
this.historyList = JSON.parse(localStorage.getItem('history'))
}
console.log(this.historyList);
},
事件 del 删除历史搜索 采用清空本地存储以及重置 historyList 数据
事件 onSearch 存储搜索数据到本地 携带查询参数跳转到搜索页面
methods: {
// 删除历史搜素
del() {
localStorage.removeItem('history')
this.historyList = []
},
onSearch() {
if (this.value) {
this.$router.push({
path: '/sear',
query: {
id: this.value //参数
}
})
// 去除首位空格
let val = this.value.trim()
if (!val) { //判断输入的值是否为空
return
}
if (this.historyList.indexOf(val) === -1) {
// 添加到头部
this.historyList.unshift(val)
// 最多显示10个
this.historyList.slice(0, 10)
localStorage.setItem('history', JSON.stringify(this.historyList))
}
} else {
this.$router.push('/sear')
}
}