Vue: Caveats for list rendering

作者 Lei Zhang 日期 2018-12-15
Vue
Vue: Caveats for list rendering

Due to limitations in JavaScript, Vue cannot detect the following changes to an array:

  1. When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue
  2. When you modify the length of the array, e.g. vm.items.length = newLength

Solution:

  1. Vue.set(vm.items, indexOfItem, newValue) or vm.$set(vm.items, indexOfItem, newValue)

    vm.items.splice(indexOfItem, 1, newValue)

  2. vm.items.splice(newLength)

Furthermore

var vm = new Vue({
data: {
a: 1
}
})
// `vm.a` is now reactive

vm.b = 2
// `vm.b` is NOT reactive

is also not reactive.

Solution:

`Vue.set(object, key, value)`

for adding a number of new properties, you can use:

Object.assign(vm.userProfile, {
age: 27,
favoriteColor: 'Vue Green'
})

P.S. (Object.assign == _.extend())

In another way:

vm.userProfile = Object.assign({}, vm.userProfile, {
age: 27,
favoriteColor: 'Vue Green'
})