vue2.0 new attribute to the data subject, and trigger a view update - $ set () usage

vue2.0 new data to the object attribute, and the view update triggers
the following code, the object to the new student age property

data () {
    return {
        student: {
            name: '',
            sex: ''
        }
    }
}

 

As we all know, directly to the student assignment, although you can add attributes, but does not trigger update view

mounted () {
    this.student.age = 24
}


The reason is: ES5 restrictions, Vue.js the object can not be detected by the properties added or deleted. Because Vue.js instance when initializing the property into getter / setter, so the property must convert it to make Vue.js on the data object is to make it responsive.

To deal with this situation, we can use $ set () method, not only can add attributes, and can trigger view updates.

写法:this.$set(this.data,”key”,value’)

mounted () {
    this.$set(this.student,"age", 24)
}

 

Guess you like

Origin www.cnblogs.com/wtsx-2019/p/12625115.html