問題引入
Vue之所以能夠監聽Model狀態的變化,是因為JavaScript語言本身提供了Proxy或者Object.observe()機制來監聽對象狀態的變化。但是,對於數組元素的賦值,卻沒有辦法直接監聽。
因此,如果我們直接對數組元素賦值
<ul>
<li v-for="(item,index) in arrInfo">{{item.name}}--{{item.age}}</li>
</ul>
data(){ return { arrInfo:[ {'name':'zuobaiquan','age':22}, {'name':'zhangsan','age':20} ] } }, // created(){ // this.arrInfo[0]={'name':'zuobaiquan01','age':22} // }, mounted(){ this.arrInfo[0]={'name':'zuobaiquan02','age':22} }
在mounted階段,直接對數組元素 arrInfo 賦值會導致Vue無法更新View
說明:在 created 視圖未渲染時 直接對數組元素 arrInfo 賦值 data里面的初值會改變的。
此時在mounted階段,簡單的做法是不要對數組元素賦值,而是更新
mounted(){ this.arrInfo[0]={'name':'zuobaiquan02','age':22} //正確做法 //this.arrInfo[0].name='zuobaiquan02' //this.arrInfo[0].age=23 }
另一種做法:通過splice()方法,刪除某個元素后,再添加一個元素,達到“賦值”的效果:
//正確做法二 通過splice()方法,刪除某個元素后,再添加一個元素,達到“賦值”的效果: var newArrItem={'name':'zuobaiquan02','age':24} this.arrInfo.splice(0, 1, newArrItem);
源碼地址:https://github.com/zuobaiquan/vue/blob/master/vueExercise/vue-test/src/views/vue-set/index01.vue
針對此問題 vue還提供了另外一種方法 set https://cn.vuejs.org/v2/api/#vm-set
調用方法:Vue.set( target, key, value )
target:要更改的數據源(可以是對象或者數組)
key:要更改的具體數據
value :重新賦的值
此時 應該這樣處理
//正確做法三 利用vue內置屬性 set var newArrItem={'name':'zuobaiquan02','age':24} this.$set(this.arrInfo,0,newArrItem)
數組更新檢測
變異方法
Vue 包含一組監聽數組的變異方法,所以它們也將會觸發視圖更新。這些方法有 push、
pop、
shift、
unshift、
splice、
sort、
reverse
替換數組
變異方法 (mutation method),顧名思義,會改變被這些方法調用的原始數組。相比之下,也有非變異 (non-mutating method) 方法,例如:filter()
, concat()
和 slice()
。這些不會改變原始數組,但總是返回一個新數組。當使用非變異方法時,可以用新數組替換舊數組:
example1.items = example1.items.filter(function (item) { return item.message.match(/Foo/) })
你可能認為這將導致 vue 丟棄現有 DOM 並重新渲染整個列表。幸運的是,事實並非如此。Vue 為了使得 DOM 元素得到最大范圍的重用而實現了一些智能的、啟發式的方法,所以用一個含有相同元素的數組去替換原來的數組是非常高效的操作。
整理:變異方法:push、
pop、
shift、
unshift、
splice、
sort、
reverse
非變異方法:filter
、 concat
、 slice
總結
由於 JavaScript 的限制,Vue 不能檢測以下變動的數組:
第一類問題:當你利用索引直接設置一個項時,例如:vm.items[indexOfItem] = newValue
第二類問題:當你修改數組的長度時,例如:vm.items.length = newLength
為了解決第一類問題,以下兩種方式都可以實現和 vm.items[indexOfItem] = newValue
相同的效果,同時也將觸發狀態更新:
// Vue.set Vue.set(example1.items, indexOfItem, newValue)
或者
// Array.prototype.splice example1.items.splice(indexOfItem, 1, newValue)
為了解決第二類問題,你可以使用 splice
:
example1.items.splice(newLength)
對象更改檢測注意事項
還是由於 JavaScript 的限制,Vue 不能檢測對象屬性的添加或刪除:
var vm = new Vue({ data: { a: 1 } }) // `vm.a` 現在是響應式的 vm.b = 2 // `vm.b` 不是響應式的
對於已經創建的實例,Vue 不能動態添加根級別的響應式屬性。但是,可以使用 Vue.set(object, key, value)
方法向嵌套對象添加響應式屬性。例如,對於:
var vm = new Vue({ data: { userProfile: { name: 'Anika' } } })
你可以添加一個新的 age
屬性到嵌套的 userProfile
對象:
Vue.set(vm.userProfile, 'age', 27)
你還可以使用 vm.$set
實例方法,它只是全局 Vue.set
的別名:
this.$set(this.userProfile, 'age', 27)
有時你可能需要為已有對象賦予多個新屬性,比如使用 Object.assign()
或 _.extend()
。在這種情況下,你應該用兩個對象的屬性創建一個新的對象。所以,如果你想添加新的響應式屬性,不要像這樣:
Object.assign(this.userProfile, { age: 27, favoriteColor: 'Vue Green' })
你應該這樣做:
this.userProfile = Object.assign({}, this.userProfile, { age: 27, favoriteColor: 'Vue Green' })
參考原文:https://www.cnblogs.com/thinkingthigh/p/7789108.html