<div class="search-box">
<a-input-search
class="search-input"
placeholder="请输入要搜索的关键词"
size="large"
enter-button
@search="onSearch"
/>
<div class="search-history">
<icon-font type="icon-lights" />
<span>搜索历史:</span>
<span v-for="(his, i) in histroys" :key="i" @click="goDetail(his)">{{ his }}</span>
</div>
</div>
在created中调用获取搜索历史的方法:
created() {
this.showHotSearch()
},
点击搜索时,执行的操作:
onSearch(value) {
this.addHotSearch(value) //调用添加搜索的方法
this.goDetail(value) //跳转页面
}
showHotSearch() {
var items = localStorage.getItem('api-hot-search') // 从本地获取
if (items) {
items = JSON.parse(items)
this.histroys = items
}
},
addHotSearch(keyword) {
keyword = String(keyword)
var items = this.histroys //historys是在data中定义的一个数组
if (items.indexOf(keyword) == -1) { //如果historys中没有,现在搜索的值
if (items.length >= 5) { // 控制historys这个数组的长度不超过5
items.pop()
}
items.unshift(keyword) //往数组的前面加上该值
}
localStorage.setItem('api-hot-search', JSON.stringify(items)) //存到本地
},