1. 程式人生 > >vue的資料雙向繫結

vue的資料雙向繫結

1.在data中設定的資料才會進行雙向繫結 2.陣列 2.1.data中的陣列,觸發陣列更新的方式有:pop、push、shift、unshift、splice、sort、reverse 2.2.而filter、slice、cancat等方式並不會改變原陣列,而是返回新陣列,因此也不能觸發更新,如果要更新陣列,以用新陣列替換舊陣列,如:

example1.items = example1.items.filter(function (item) {
  return item.message.match(/Foo/)
})

2.3.注意:改變陣列某一項的值時不會觸發更新,改變陣列長度也不會觸發更新,如

data: {
    arr: [1, 2, 4]
}
this.arr[1] = 5 // 此時並不能觸發更新
this.arr.length = 4 // 也不觸發更新

解決方案:1.使用$setthis.$set(arr, indexOfItem, newValue) 2.使用splicethis.arr.splice(indexOfItem, newValue) 3.物件 3.1.vue不能檢測物件屬性的新增或刪除

data: {
    obj: {
        name: 'mary'
    }
}
this.obj.age = 18
//新新增的屬性,無法檢測到

解決方法:使用$set,this.$set(obj, property, value) 2.2.新增多個屬性時,也可以使用Object.assign

vm.userProfile = Object.assign({}, vm.userProfile, {
  age: 27,
  favoriteColor: 'Vue Green'
})
但切記不能這樣寫
Object.assign(vm.userProfile, {
  age: 27,
  favoriteColor: 'Vue Green'
})