Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

如何删除localStorage储存数组中的指定对象

我在使用Vue.js做一个评论列表的demo的时候,将输入框输入的用户名和评论内容存储在localStorage中并通过列表展示,我想通过点击实现删除对应的评论,同时更新localStorage中的数据。

这是子组件中存储数组的方法:

postComment(){
            
    var comment = {id:Math.random(),user:this.user, content:this.content};

    // 从localStorage中获取所有的评论
    var list = JSON.parse(localStorage.getItem('cmts')||'[]');
    list.unshift(comment)
    // 保存最新的评论数据
    localStorage.setItem('cmts',JSON.stringify(list))
    this.user = this.content = ''

    this.$emit('func')
}

删除评论的方法:

del(id){
        this.list.some((item,i)=>{
            var list = JSON.parse(localStorage.getItem('cmts')||'[]');
            if(item.id === id){
                this.list.splice(i,1);
                return true;
            }
             // 将删除对应数据后新的评论列表存到list中
        localStorage.removeItem('cmts',JSON.stringify(list));
    })
            }

这是存储在localStorage中的数组:
无标题.png

使用removeItem()会把整个list数组给删除了:

 localStorage.removeItem('cmts',JSON.stringify(list));

尝试过在使用some方法删除评论后,重新将list数组存储到localStorage当中去,但list数组没更新。
我想知道怎么通过id值删除localStorage中存储的list数组的对应对象。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

把数组对应项删除后,再储存新的数组即可:

del(id){
    this.list.splice(this.list.findIndex(item => item.id === id), 1);
    localStorage.setItem('cmts',JSON.stringify(this.list))
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...