为什么 'updated' 在组件的数组属性已更改时不会被触发?

Why doesn't 'updated' get fired for a component when it has an array prop that is changed?

我用一个数组类型的道具创建了一个子组件。我希望只要使用 push() 从父级修改该数组,就会触发 updated 生命周期事件。这不会发生。我可以看到更改在父状态中生效,但这些更改似乎没有被子组件检测到。我错过了什么?

示例代码

See a 'working' demo on codepen.io

我的观点

<div id="app">
  <child :items="items"></child>
  <button type="button" v-on:click="addItem()">Add Item</button>
</div>

我的脚本

// Child component
Vue.component('child', {
  template: '<div>{{itemCount}}</div>',
  props: {
   items: Array
  },
  data: function() { 
    return { itemCount: 0 }
  },
  updated: function() {
    this.itemCount = this.items.length;
  }
})

// Main app
var app = new Vue({
  el: '#app',
  data: {
    items: []
  },
  methods: {
    addItem: function() {
      this.items.push(Math.random());
    }
  }
});

如果您注意到 updated 的文档,它说:

Called after a data change causes the virtual DOM to be re-rendered and patched.

但在您的情况下,您没有在子组件 DOM 的任何位置使用 items,因此数据更改对虚拟 DOM 没有影响,更新是未被调用。

如果你只是在子组件的div中添加items,它就会开始工作:

// 子组件

Vue.component('child', {
  template: '<div>{{items}}::::{{itemCount}}</div>',
  props: {
   items: Array
  },
  ...
  ...
})

查看工作代码笔 here

尝试使用计算的 属性 而不是 updated 回调。

computed:{ itemCount(){ return this.items.length } }