今天做一个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);
}
},
以上代码运行成功!
作者:虫鸣
链接:https://www.jianshu.com/p/ec1363a8a0eb
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
本文解决了一个在VUE项目中使用splice方法删除数组元素时出现的cannotreadproperty‘splice’ofundefined错误。通过调整代码中this关键字的引用,成功实现了数组元素的删除。
227

被折叠的 条评论
为什么被折叠?



