vue2.0 給data對象新增屬性,並觸發視圖更新
如下代碼,給 student對象新增 age 屬性
data () {
return {
student: {
name: '',
sex: ''
}
}
}
衆所周知,直接給student賦值操作,雖然可以新增屬性,但是不會觸發視圖更新
mounted () {
this.student.age = 24
}
原因是:受 ES5 的限制,Vue.js 不能檢測到對象屬性的添加或刪除。因爲 Vue.js 在初始化實例時將屬性轉爲 getter/setter,所以屬性必須在 data 對象上才能讓 Vue.js 轉換它,才能讓它是響應的。
要處理這種情況,我們可以使用$set()方法,既可以新增屬性,又可以觸發視圖更新。
但是,值得注意的是,網上一些資料寫的$set()用法存在一些問題,導致在新接觸這個方法的時候會走一些彎路!
錯誤寫法:this.$set(key,value)
mounted () {
this.$set(this.student.age, 24)
}
正確寫法:this.$set(this.data,”key”,value’)
mounted () {
this.$set(this.student,"age", 24)
}