vue生命周期

2020-12-15  本文已影响0人  3e2235c61b99

vue生命周期除了下图中的beforeCreate, created, beforeMount, mounted, beforeUpdate, updated, beforeDestroy, destroyed8个,还有和keep-alive相关的两个生命周期activated, deactivated,和一个捕获子孙组件错误的生命周期errorCaptured
activated 被 keep-alive 缓存的组件激活时调用。
deactivated 被 keep-alive 缓存的组件停用时调用。
errorCaptured 当捕获一个来自子孙组件的错误时被调用。此钩子会收到三个参数:错误对象、发生错误的组件实例以及一个包含错误来源信息的字符串。此钩子可以返回 false 以阻止该错误继续向上传播。

<template>
    <div>
        <div>生命周期</div>
        <child></child>
    </div>
</template>

<script>
    import child from "../assembly-test/child";
    export default {
        name: "index",
        data() {
            return {
                msg: "生命周期"
            }
        },

        components: {
            child
        },

        beforeCreate() {
            console.log("beforeCreate")
        },

        created() {
            console.log("created")
        },

        beforeMount() {
            console.log("beforeMount")
        },

        mounted() {
            console.log("mounted")
        },

        beforeUpdate() {
            console.log("beforeUpdate")
        },

        updated() {
            console.log("updated")
        },

        activated() {
            console.log("activated")
        },

        deactivated() {
            console.log("deactivated")
        },

        beforeDestroy() {
            console.log("beforeDestroy")
        },

        destroyed() {
            console.log("destroyed")
        },

        errorCaptured(err, vm, info) {
            console.log("errorCaptured")
            return false
        },
    }
</script>
1-1.页面无缓存

当前页面没有被keep-alive缓存,且未引入子组件时,进入当前页面控制台输出

beforeCreate
created
beforeMount
mounted

离开当前页面控制台输出:

beforeDestroy
destroyed
1-2,页面被缓存

当前页面被keep-alive缓存,且未引入子组件时,进入当前页面控制台输出

beforeCreate
created
beforeMount
mounted
activated

离开当前页面控制台输出:

deactivated
beforeDestroy
destroyed

相比无缓存时,多执行了两个生命周期钩子,进入页面时执行activated,离开页面时执行deactivated

2.页面更新

当前页面引入子组件时,进入当前页面控制台输出

beforeCreate
created
beforeMount
mounted
activated
beforeUpdate
updated
3.子组件报错

当前页面引入的子组件报错时,控制它输出

beforeCreate
created
beforeMount
errorCaptured
mounted
activated
beforeUpdate
updated

当在初始加载时子组件就报错,会在mounted之前执行errorCaptured生命周期钩子
如果感觉错误无关紧要或者不想把错误传递到外层,可以在errorCapturedreturn false阻止错误继续向上传播

lifecycle.png
上一篇 下一篇

猜你喜欢

热点阅读