cannot read property 'splice' of undefined错误解决

今天做一个VUE的数组元素删除操作,使用的是splice.
然而运行后发现一直提示"cannot read property 'splice' of undefined".代码如下:

        new Vue({
            el:'#app',
            data:{
                items:[
                    {name:"test1",val:2},
                    {name:"test2",val:3},
                    {name:"test3",val:4},
                ]
            },

            methods:{
                reduce:function(){
                    this.items.forEach(function(item,index){
                        item.val-=1;
                        if(item.val==0){
                            this.items.splice(index,1);
                        }
                    })
                    console.log(this.items);
                }
            },

以上代码运行后,一直提示"cannot read property 'splice' of undefined",经过排查,原来是由于forEach里面的this指向已经不是vue实例造成的.
修改代码如下:

        new Vue({
            el:'#app',
            data:{
                items:[
                    {name:"test1",val:2},
                    {name:"test2",val:3},
                    {name:"test3",val:4},
                ]
            },

            methods:{
                reduce:function(){
                       var that=this;
                    that.items.forEach(function(item,index){
                        item.val-=1;
                        if(item.val==0){
                            that.items.splice(index,1);
                        }
                    })
                    console.log(that.items);
                }
            },

以上代码运行成功!

你可能感兴趣的:(cannot read property 'splice' of undefined错误解决)