代码之家  ›  专栏  ›  技术社区  ›  Sphinx

hook=componentupdated of vue指令未触发

  •  4
  • Sphinx  · 技术社区  · 8 年前

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

    AS Vue official Guide 说:

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

    看起来 组件已更新 应该被触发。

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

    在下面的演示中,点击 点击我! 然后你会看到 组件已更新 不被调用。

    但是当点击 更改数据 (执行类似的行为 点击我! ,不同的是它更改父组件上的数据),它将正确触发。

    非常感谢。

    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>
    1 回复  |  直到 8 年前
        1
  •  1
  •   Sphinx    8 年前

    基于 Vue Team Feedback ,这不是一个悬而未决的问题= 组件已更新 ,这是我对单词的误解。

    对于钩子的先决条件= 已更新组件 被触发时,指令绑定到的vnode已经更改。这意味着,如果只有子vnode发生变化,vue可能不会像@jacob goh在评论中所说的那样(只会单向流动)。

    所以 组件已更新 并不意味着它会检测到子组件是否更新,它只意味着 什么时候 将被触发。