Vue生命周期

Vue生命周期

在组件化开发时,页面也是一个组件,一个组件就是一个Vue的对象,而Vue对象是有生命周期,从创建那一刻到销毁的过程叫生命周期,或者说,一个组件从创建到销毁的过程叫生命周期。

Vue生命周期的8个钩子函数,分别会在不用时期执行。

钩子函数 描述
beforeCreate 创建Vue实例之前调用
created 创建Vue实例成功后调用(可以在此处发送异步请求后端数据)
beforeMount 渲染DOM(挂载)之前调用
mounted 渲染DOM(挂载)之后调用
beforeUpdate 重新渲染之前调用(数据更新等操作时,控制DOM重新渲染)
updated 重新渲染完成之后调用
beforeDestroy 销毁之前调用
destroyed 销毁之后调用

生命周期图

官方原图

image

理解的图

python/vue/3-Vue生命期钩子 | Justin-刘清政的博客 (liuqingzheng.top)

image

测试生命周期

<div id="app">
    <button @click="showChild">显示组件/删除组件</button>
    <child v-if="show"></child>
</div>
<script>
    // 创建组件
    Vue.component('child', {
        // 组件内容
        template: `
            <div>
                <h1>{{ name }}</h1>
            </div>
        `,
        data() {
            return {
                name: '定时器',
                t: null,  // 存定时器对象
            }
        },
        methods: {},
        // 生命周期
        beforeCreate() {
            console.log('beforeCreate')
        },
        // 创建时启动定时任务
        created() {
            console.log('created')
            // 定时任务,1秒一次
            this.t = setInterval(() => {
                console.log('1s过去了')
            }, 1000)
        },
        beforeMount() {
            console.log('beforeMount')
        },
        mounted() {
            console.log('mounted')
        },
        beforeUpdate() {
            console.log('beforeUpdate')
        },
        updated() {
            console.log('updated')
        },
        beforeDestroy() {
            console.log('beforeDestroy')
            console.log('组件销毁,删除定时器')
            clearInterval(this.t)
            this.t = null
        },
        destroyed() {
            console.log('destroyed')
        }
    })

    const vm = new Vue({
        el: '#app',
        data: {
            show: false,
        },
        methods: {
            showChild() {
                this.show = !this.show
            }
        }
    })
</script>

image

posted @ 2022-06-28 18:12  Yume_Minami  阅读(46)  评论(0编辑  收藏  举报