全部 / 前端 / 技术 · 2022年9月19日 0

Vue 中 @hook 的使用

hook

同一个组件内使用

事件监听和移除

mounted(){
    window.addEventListener('online',this.handleOnline)
    this.$once('hook:beforeDestroy',function() {
      window.removeEventListener('online',this.handleOnline)
    })
}

定时器清除

mounted() {
      const timer = setInterval(() => { ... }, 1000);
      this.$once('hook:beforeDestroy', () => clearInterval(timer);)
}

父子组件(子组件可控)

// 父组件:
<Child @mounted="handleMounted"></Child>

// 子组件:
mounted() {
  this.$emit("mounted");
}

改进:

// 父组件:
<Child @hook:mounted="handleMounted"></Child>
// 子组件:
mounted() {
  // 不需要写
}

父子组件(子组件不可控)

若想监听第三方组件,没有办法改它们的源码,只能通过 hook 方式:

<ThirdComponent @hook:mounted="handleMounted"></ThirdComponent>