vue双向绑定原理是通过Object.defineProperty()来对对象的setter和getter属性进行操作。
为了保证视图动态更新需要给对象加上get和set方法来进行双向绑定。
1.动态更新对象
给man添加age属性
错误方法:
add(){
this.man.age = '22'
console.log(this.man)
},
正确方法:
add(){
this.$set(this.man,'age','22')
console.log(this.man)
},
2.动态更新数组
给man添加添加学生小陈的信息
student:[
{name:'小红',age:'12'},
{name:'小李',age:'15'},
]
小陈:{name:'小陈',age:'13'}
错误方法:
add(){
let schen = {name:'小陈',age:'13'}
this.student[2] = schen
console.log(this.student)
},
正确方法:
add(){
let schen = {name:'小陈',age:'13'}
this.$set(this.student,2,schen)
console.log(this.student)
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。