Vue用localStorage保存搜索历史记录/清空记录

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 = [];
},
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值