data:{
persons:[
{id:'001',name:'1',age:30,sex:'女'},
{id:'002',name:'2',age:31,sex:'女'},
{id:'003',name:'3',age:18,sex:'男'},
{id:'004',name:'4',age:19,sex:'男'}
]
},
methods: {
update5(){
// this.persons[0] = {id:'001',name:'xxx',age:50,sex:'男'} //不奏效
this.persons.splice(0,1,{id:'001',name:'xxx',age:50,sex:'男'})
}
}
可以发现使用 this.persons[0] = {id:'001',name:'xxx',age:50,sex:'男'}
是VUE是不承认的,原因是因为VUE在数组里没有getter和setter。所以我们之间添加不行。
this.persons[0].name = '马老师' //奏效
this.persons[0].age = 50 //奏效
this.persons[0].sex = '男' //奏效
但是上面这个方法又是可以的,那是因为数组里的每个值都有getter和setter,所以VUE是承认的。
虽然VUE不承认直接赋值,但是VUE作为一个成熟的框架肯定想到了这一点,所以给我们了解决方法,
查了一下官网,发现官网也有提示我们。这样是不行的。
官网推荐我们解决的方法是
第一种方法:this.$set( this.persons,0, {id:'001',name:'xxx',age:50,sex:'男'})
第二种方法:this.persons.splice(0,1,{id:'001',name:'xxx',age:50,sex:'男'})
当然肯定不止一种对数组的方法
当然无法新增对象也是一样的道理,这里就不具体说了。也是可以使用this.$set方法