Vue监听子组件生命周期

301 阅读1分钟

子组件动态的开关当前组件生命周期监听 on,on, off, $once

export default Vue.extend({
  data() {
    return {
      canMounted: false,
      canUpdated: false,
    }
  },
  methods: {
    onUpdated() {
      this.$off('hooks:updated', this.onUpdated); //关闭额外监听事件
      this.canUpdated = false;
    }
  },
  created () {
    !this.canMounted && this.$options['mounted'] = null // 删除组件的mounted
    this.canUpdated && this.$on('hooks:updated', this.onUpdated) // 额外监听组件生命周期
  },
  mounted() {
    console.log('mounted')
  },
})

监听子组件生命周期 @hook:created, @hook:mounted

<el-button ref="btn" @hook:created="log" >

通过获取实例监听子组件生命周期

export default Vue.extend({
  beforeCreate () {
    const refs = this.$refs
    const refKey = 'container'
    if(refs){
      Object.defineProperty(refs, refKey, {
        enumerable: true,
        configurable: true,
        get() {
          return this['_' + refKey]
        },
        set(value) {
          this['_' + refKey] = value;
          if(value instanceof Vue){
            value.$once('hook:mounted', () => console.log('hack child mounted'))
          }
        }
      })
    }
  },
})