一、数组
1、当直接用索引直接设置一个项的时
例如:this.arr[index] = newArr
解决方法:this.$set(this.arr,index,newArr);
2、当直接修改数组长度时
例如:this.arr.length = newLength
解决方法:this.items.splice(index,1,newArr) 或者this.items.splice(newLength)
二、对象
1、由于Javascript的限制,Vue不可以检测对象属性的添加或删除
var obj = [{
a:1,
b:2
},{
a:1,
b:2
}
]
obj.forEach((item,index)=>{
obj[index].c = 3;
})
对于已经创建的实例,Vue不能动态的添加根级别的响应式属性,如想实现对象属性的添加可使用
obj.forEach((item,index)=>{
this.$set(obj[index],'c',3)
})
2、如需要为已有的对象赋予多个新的属性,比如使用Object.assign()或_.extend(),
在这种情况下你想应该用两个对象的属性创建一个新的对象,所以如果你想添加新的响应式属性你应该这样做
var userProfile = [a:1];
userProfile = Object.assign({
},userProfile,{
b:2,
c:3
})
console.log(userProfile)
//[a:1,b:2,c:3]