美文网首页
vue钩子函数hook的用法

vue钩子函数hook的用法

作者: chxuu | 来源:发表于2020-10-27 14:18 被阅读0次
    1. 在父组件监听子组件的生命周期
    // 父组件监听子组件mounted
    <el-child @hook:mounted="handleChildMounted"></el-child>
    <script>
        handleChildMounted () {
            // do something
        }
    <script>
    
    
    1. 程序化的事件侦听器
    this.$on/$once('hook:生命周期',callback)
    

    在实际运用中,我们常在mounted生命周期中,使用hook监听beforeDestroy,在beforeDestroy内部处理代码的清理和销毁工作。这样做的好处是代码的处理和清除是在一起的,从代码组织上来看,更友好。

    mounted () {
      bus.$on('pageSize', this.handlePageSize);
      this.timer = setInterval(() => {
          // dosomething 
     }, 1000)
     this.$once('hook:beforeDestroy', () => {
        // 销毁定时器
        clearInterval(this.timer);
        // 清除事件监听
        bus.$off('pageSize', this.handlePageSize);
    })
    
    pageSize ( ) {
        // do something
    }
    }
    

    相关文章

      网友评论

          本文标题:vue钩子函数hook的用法

          本文链接:https://www.haomeiwen.com/subject/hncxvktx.html