直接修改數組元素是無法觸發視圖更新的,如
this.array[0] = { name: 'meng', age: 22 }
修改array的length也無法觸發視圖更新,如
this.array.length = 2;
觸發視圖更新的方法有如下幾種
1. Vue.set
可以設置對象或數組的值,通過key或數組索引,可以觸發視圖更新
數組修改
Vue.set(array, indexOfItem, newValue) this.array.$set(indexOfItem, newValue)
對象修改
Vue.set(obj, keyOfItem, newValue) this.obj.$set(keyOfItem, newValue)
2. Vue.delete
刪除對象或數組中元素,通過key或數組索引,可以觸發視圖更新
數組修改
Vue.delete(array, indexOfItem) this.array.$delete(indexOfItem)
對象修改
Vue.delete(obj, keyOfItem) this.obj.$delete(keyOfItem)
3. 數組對象直接修改屬性,可以觸發視圖更新
this.array[0].show = true; this.array.forEach(function(item){ item.show = true; });
4. splice方法修改數組,可以觸發視圖更新
this.array.splice(indexOfItem, 1, newElement)
5. 數組賦值為新數組,可以觸發視圖更新
this.array = this.array.filter(...) this.array = this.array.concat(...)
6. 用Object.assign或lodash.assign可以為對象添加響應式屬性,可以觸發視圖更新
//Object.assign的單層的覆蓋前面的屬性,不會遞歸的合並屬性 this.obj = Object.assign({},this.obj,{a:1, b:2}) //assign與Object.assign一樣 this.obj = _.assign({},this.obj,{a:1, b:2}) //merge會遞歸的合並屬性 this.obj = _.merge({},this.obj,{a:1, b:2})
7.Vue提供了如下的數組的變異方法,可以觸發視圖更新
push()
pop()
shift()
unshift()
splice()
sort()
reverse()