美文网首页
Vue 数组更新检测

Vue 数组更新检测

作者: 飞鱼_JS | 来源:发表于2018-04-04 15:38 被阅读0次

变异方法

  • Vue 包含一组观察数组的变异方法,所以它们也将会触发视图更新
push()
pop()
shift()
unshift()
splice()
sort()
reverse()

替换数组

  • 非变异 (non-mutating method) 方法,例如:filter(), concat() 和 slice() 。这些不会改变原始数组,但总是返回一个新数组。当使用非变异方法时,可以用新数组替换旧数组:
example1.items = example1.items.filter(function (item) {
  return item.message.match(/Foo/)
})

注意事项

  • Vue 不能检测以下变动的数组:
    当你利用索引直接设置一个项时,例如:vm.items[indexOfItem] = newValue
    当你修改数组的长度时,例如:vm.items.length = newLength
var vm = new Vue({
  data: {
    items: ['a', 'b', 'c']
  }
})
vm.items[1] = 'x' // 不是响应性的
vm.items.length = 2 // 不是响应性的
  • 解决方法
//方法一
// Vue.set
Vue.set(vm.items, indexOfItem, newValue)
//方法二
// Array.prototype.splice
vm.items.splice(indexOfItem, 1, newValue)
//方法三
vm.$set(vm.items, indexOfItem, newValue)

相关文章

网友评论

      本文标题:Vue 数组更新检测

      本文链接:https://www.haomeiwen.com/subject/qngkhftx.html