vue數組對象修改觸發視圖更新

直接修改數組元素是沒法觸發視圖更新的,如數組

this.array[0] = {
    name: 'meng',
    age: 22
}

修改array的length也沒法觸發視圖更新,如this

this.array.length = 2;

觸發視圖更新的方法有以下幾種spa

1. Vue.setcode

能夠設置對象或數組的值,經過key或數組索引,能夠觸發視圖更新對象

數組修改blog

Vue.set(array, indexOfItem, newValue)
this.array.$set(indexOfItem, newValue)

對象修改遞歸

Vue.set(obj, keyOfItem, newValue)
this.obj.$set(keyOfItem, newValue)

2. Vue.delete索引

刪除對象或數組中元素,經過key或數組索引,能夠觸發視圖更新it

 

數組修改io

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()
相關文章
相關標籤/搜索