钩子函数=Vue指令的componentUpdated未被触发

4
我遇到了一个问题,如果一个组件只更新自己的数据,它将不会触发指令在父组件中的componentUpdated钩子。 正如Vue官方指南所说:

componentUpdated:在包含组件的VNode和其子级的VNode更新后调用。

看起来应该触发componentUpdated。 我做错了什么?还是理解有误? 在下面的演示中,点击Click Me!按钮,然后您将看到componentUpdated没有被调用。 但是当点击change data(执行与click me!类似的行为,区别在于它更改父组件中的数据)时,它将正确触发。 非常感谢任何帮助。

Vue.config.productionTip = false
Vue.component('child', {
  template: `<div>{{point}}
                <span style="background-color:gray;font-weight:bold;color:red">
                  -{{mytest}}
                </span>
                <button @click="plusOne()">Click me!</button>
             </div>`,
  props: ['point'],
  data(){
    return {
      mytest: 1
    }
  },
  updated: function () {
    console.log('updated component=child')
  },
  methods: {
    plusOne() {
      this.mytest += 1
    }
  }
})

let vMyDirective = {}
vMyDirective.install = function install (Vue) {

  Vue.directive('my-directive', {
    inserted: function () {
      console.log('!!!directive for inserted')
    },
    bind: function bind (el, binding, vnode) {
      console.log('!!!directive for bind')
    },
    componentUpdated: function componentUpdated (el, binding, vnode) {
      console.log('!!!directive for component updated')
    },
    update: function () {
      console.log('!!!directive for update')
    }
  })
}

Vue.use(vMyDirective)

new Vue({
  el: '#app',
  data() {
    return {
      testValues: ['label a', 'label b'],
      testIndex: 1
    }
  },
  methods:{
    pushArray: function() {
      this.testValues.push('label c')
    },
    changeData: function () {
      this.testIndex += 1
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
  <button v-on:click="pushArray()">Add one Child!!!</button>
  <button v-on:click="changeData()">Change Data - {{testIndex}}</button>
  <div v-my-directive>
    <child v-for="(item, index) in testValues" :key="index" :point="item"></child>
  </div>
</div>


好问题。显然这非常值得成为新的Vue Issue。在这种情况下,文档可能会引导错误。就像在React中一样,在Vue中,数据只能单向流动,即从父组件到子组件。如果这样做了,可能会引起许多其他问题。 - Jacob Goh
@JacobGoh 这可能是正确的,如果是这样的话,那么指南应该使用准确的描述,比如 componentUpdated: 在包含组件的 VNode 和其子节点的 VNode 被重新挂载后调用。 - Sphinx
1个回答

1
根据Vue团队反馈,这不是关于hook=componentUpdated的一个问题,而是我的对话术理解有误。 对于触发hook=componentUpdated的先决条件,它是指指令绑定到的VNode已经更改。也就是说,如果仅更改子级VNode,则Vue将无法正确捕获,就像@Jacob Goh在评论中所说的那样(仅单向流动)。 因此,componentUpdated并不意味着它会检测子组件是否已更新,它只表示何时将被触发。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,