【问题标题】:Hook=componentUpdated of Vue directive not triggered未触发 Vue 指令的 Hook=componentUpdated
【发布时间】:2018-11-11 02:01:34
【问题描述】:

我刚遇到一个问题,如果一个组件只更新自己的数据,它不会触发父组件的指令的hook=componentUpdated

正如Vue official Guide所说:

componentUpdated:在包含组件的 VNode 和 其子节点的 VNode 已更新。

似乎应该触发componentUpdated

我做错了吗?还是误会了什么?

在下面的演示中,点击 Click Me! 按钮,您将看到 componentUpdated 未被调用。

但是当点击更改数据(与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>

【问题讨论】:

  • 好问题。显然这是非常值得成为new Vue Issue。在这种情况下,文档可能具有误导性。就像在 React 中一样,在 Vue 中,数据只有一种方式流动,即从父级到子级。如果这行得通,它可能会导致很多其他问题。
  • @JacobGoh 这可能是真的,如果是这样,可能指南应该使用准确的描述,如componentUpdated: called after the containing component’s VNode and the VNodes of its children have been remounted.

标签: javascript vue.js vuejs2


【解决方案1】:

基于Vue Team Feedback,这不是一个问题=componentUpdated,是我对文字的误解。

对于钩子=comopnentUpdated的先决条件被触发,它是指令绑定到的VNode已经改变。这意味着如果只有子 VNode 发生变化,Vue 可能不会像 @Jacob Goh 在 cmets 中所说的那样捕获它(仅以一种方式流动)。

所以componentUpdated并不意味着它会检测到子组件是否更新,它只是意味着何时会被触发。

【讨论】:

    猜你喜欢
    • 2019-08-10
    • 2021-07-28
    • 2023-01-31
    • 1970-01-01
    • 2021-02-24
    • 2013-08-25
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多