Vue钩子函数之钩子事件hookEvent,监听组件

Vue当中,hooks可以作为一种event,在Vue的源码当中,称之为hookEvent。 

 

Vue组件中,可以用过$on,$once去监听所有的生命周期钩子函数,如监听组件的updated钩子函数可以写成 this.$on('hook:updated', () => {})

 

示例:使用hook之前


使用hook之后,监听组件

export default {
  mounted() {
    this.chart = echarts.init(this.$el)
    // 请求数据,赋值数据 等等一系列操作...
    
    // 监听窗口发生变化,resize组件
    window.addEventListener('resize', this.$_handleResizeChart)
    // 通过hook监听组件销毁钩子函数,并取消监听事件
    this.$once('hook:beforeDestroy', () => {
      window.removeEventListener('resize', this.$_handleResizeChart)
    })
  },
  updated() {},
  created() {},
  methods: {
    $_handleResizeChart() {
      // this.chart.resize()
    }
  }
}

监听第三方组件数据的变化,但是组件又没有提供change事件,同事也没办法了,才想出来要去在外部监听组件的updated钩子函数。查看了一番资料,发现Vue支持在外部监听组件的生命周期钩子函数。


 

你可能感兴趣的:(vue2.0,vue3.0)