Vue搜索历史记录/清空记录
1.搜索后保存
历史记录, localStorage.setItem(key,value)
2.在保存前
,先判断数组中是否已存
在记录(有:则清除该记录
),并将搜索值unshift进数组首位
setLocalHistory() {
/** 先判断*/
this.getLocalKey()
/** 搜索历史*/
// 没有搜索记录,把搜索值push进数组首位,存入本地
if (!this.historyList.includes(this.value)) {
this.historyList.unshift(this.value);
localStorage.setItem("historyList", JSON.stringify(this.historyList));
}else{
//有搜索记录,删除之前的旧记录,将新搜索值重新push到数组首位
let i = this.historyList.indexOf(this.value);
this.historyList.splice(i,1)
this.historyList.unshift(this.value);
localStorage.setItem("historyList", JSON.stringify(this.historyList));
}
this.$forceUpdate()
},
/** 判断 localStorage中 是否有 historyList*/
getLocalKey() {
//如果本地存储的数据historyList有值,直接赋值给data中的historyList
if (JSON.parse(localStorage.getItem("historyList"))) {
this.historyList = JSON.parse(localStorage.getItem("historyList"));
}else {
this.historyList = []
}
},
/** 清空历史搜索记录 */
empty(){
this.$message({
type: "success",
message: '清空历史搜索成功'
});
localStorage.removeItem('historyList');
this.historyList = [];
},