vue2中的hookEvent

110 阅读1分钟

使用场景一:可以将多个生命周期的逻辑统一写到一个生命周期中

    export default {
        ...
        created() {
            console.log('created');
            this.$on('hook:beforeMount', () => {
                console.log('在beforeMount周期里要处理的相关逻辑');
            });
            this.$on('hook:mounted', () => {
                console.log('在mounted周期里要处理的相关逻辑');
            });
            this.$on('hook:beforeDestroy', () => {
                console.log('在beforeDestroy周期里要处理的相关逻辑'); // 比如销毁定时器
            });
        }
    };

image.png

按照生命周期执行的先后顺序,在created里面只能写其之后的生命周期。

使用场景二:监听子组件的生命周期是否执行完毕

    // 父组件:
    <Children @hook:mounted="ChildrenRender" />

    export default {
        name: 'Parent',
        components: { Children },
        methods: {
            ChildrenRender() {
                console.log('子组件mounted已完成');
            }
        },
        mounted() {
            console.log('parent mounted');
        }
    };
    
    // 子组件:
    export default {
        name: 'Children',
        mounted() {
            console.log("children mounted");
        }
    };

打印结果:

image.png