$options.data() 重置屬性

使用方法

Object.assign(this.$data, this.$options.data()); 

問題

如果data()中若使用了this來訪問props或methods,在重置完$data時,this.methodA和this.B爲undefined。

原因

和Vue實例的初始化相關。
1、new Vue的時候傳了一個對象,把該對象記爲options,Vue將options中自定義的屬性和Vue構造函數中定義的屬性合併爲vm.optionsvm.options,vm.options.data()中的this指向vm.optionsmethodABvm.options,而methodA和B並沒有直接掛在vm.options下,所以this.methodA和this.B爲undefined。

解決方法

// 指定this
Object.assign(this.$data, this.$options.data.call(this));
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章