用localstorage存取历史记录
1.在searchResult页面存取
// 将搜索关键字设置到缓存中
saveHisByLocal(keyword) {
// 判断搜索记录是否存在,如果存在,不需要存
this.searchShopsHis.forEach((item, index) => {
if(item == keyword) {
return false;
}
})
2.记录长度为5
if(this.searchShopsHis.length >= 5) {
this.searchShopsHis.pop();
}
// 将搜索的记录保存到第一位
this.searchShopsHis.unshift(keyword)
// 保存到localStorage
localStorage.searchShopsHis = JSON.stringify(this.searchShopsHis);
},
3.在searchResult页面取缓存记录
getHisByLocal() {
// 从缓存获取搜索记录
let searchShopsHis = localStorage.searchShopsHis;
if(searchShopsHis) {
this.searchShopsHis = JSON.parse(searchShopsHis);
}
},
4.在searchResult的mounted中调用取出缓存
this.getHisByLocal();
5.在search页面取
mounted() {
// 进入页面获取搜索记录
this.getHisByLocal();
},
methods: {
getHisByLocal() {
// 从缓存获取搜索记录
let searchShopsHis = localStorage.searchShopsHis;
if(searchShopsHis) {
this.searchShopsHis = JSON.parse(searchShopsHis);
}
},
6.在searchResult页面渲染
<span v-for="(item, index) in searchShopsHis" :key="index">{{item}}</span>