Vue – $set dynamically updates objects / arrays

Time:2021-8-14

Vue bidirectional binding principle is to operate the setter and getter properties of an object through object. Defineproperty().
In order to ensure the dynamic update of the view, we need to add get and set methods to the object for two-way binding.

1. Dynamically update objects
Add age attribute to man
Error method:
add(){
this.man.age = ’22’
console.log(this.man)
},
Vue - $set dynamically updates objects / arrays
Correct method:
add(){
this.$set(this.man,’age’,’22’)
console.log(this.man)
},
Vue - $set dynamically updates objects / arrays

2. Dynamically update array
Add student Chen’s information to man
student:[

{Name: 'Xiaohong', age: '12'},
{Name: 'Xiao Li', age: '15'},

]
Xiao Chen: {Name: ‘Xiao Chen’, age: ’13’}

Error method:
add(){
Let schen = {Name: ‘Xiao Chen’, age: ’13’}
this.student[2] = schen
console.log(this.student)
},
Vue - $set dynamically updates objects / arrays

Correct method:
add(){
Let schen = {Name: ‘Xiao Chen’, age: ’13’}
this.$set(this.student,2,schen)
console.log(this.student)
}
Vue - $set dynamically updates objects / arrays