js localStorage写浏览记录,并删除单条记录和从记录中取值

在做一个选择商品时,需要保存用户的查找记录,类似与淘宝的历史记录,我是用的localStorage,菜鸟一枚,各大神指点

将用户每次浏览的数据push到数组中,每浏览一次push一次,

然后将数组转成字符串JSON.stringify(arr),然后存储到本地

remb: function (Odata, title, key) {
            var that = this;
            //存储浏览记录//key 0国产,1进口,2VIN
            var arr = [];
            arr.push({ "value": Odata, "title": title, "key": key });
            if (that.setstg != null) {
                if (that.setstg.length != 0) {
                    that.setstg = that.setstg.concat(arr);
                } else {
                    that.setstg = arr;
                }
            } else {
                that.setstg = arr;
            }
            var str = JSON.stringify(that.setstg);
            localStorage.setItem('local', str);
            this.setstg = JSON.parse(localStorage.getItem('local'));
            console.log('记录', that.setstg);
        },

选择一条浏览记录

 // 选择浏览记录
        sel_contry: function (num) {
            var that = this;
            this.con_index = num;
            if (num == 1) {
                var str = JSON.parse(localStorage.getItem('local'))
                if (str != null) {
                    that.setstg = str;
                    console.log('点击记录', that.setstg)
                } else {
                    that.setstg = [];
                }

            }


        },

删除一条浏览记录,需从数组中删除此条,其余保存本地

  // 删除一条记录
        delete_this: function (index) {
            var that = this;
            if (that.setstg.length != 0) {
                that.setstg.splice(index, 1);
                console.log(that.setstg)
                that.setstg = that.setstg;
            }
            localStorage.setItem('local', JSON.stringify(that.setstg));

        },

各大神有更好的办法,欢迎指点


你可能感兴趣的:(localStorage,本地存储,用户浏览记录,历史记录,js,vue)