少侠请重新来过 - Vue学习笔记(二) - Vue生命周期

273 阅读1分钟

Vue 生命周期和钩子

每一个vue实例创建时,会经历一段初始化的过程,同时会调用其生命周期钩子,实例的钩子this指向它的Vue实例,不需要在钩子用箭头函数。

Vue生命周期和钩子示例图

<template>
    <div>
        <p>{{msg}}</p>
    </div>
</template>

<script>
export default {
    data(){
        return{
            msg:'vue'
        }
    },
    beforeCreate() {
        //组件刚刚被创建,组件属性计算之前时调用
        console.log('-- beforeCreate --');       // 输出 -- beforeCreate --
        console.log(`this.msg = ${this.msg}`);   // 输出 undefined
        console.log(`this.$el = `);              // 输出 this.$el =
        console.log(this.$el)                    // 输出 undefined
    },
    created() {
        //组件刚刚创建完成,属性已经绑定,但是还未生成dom节点,所以$el不存在,msg已经被绑定
        this.log('created')
        // 输出 -- created --
        // 输出 this.msg = vue
        // 输出 this.$el =
        // 输出 undefined
    },
    beforeMount() {
        //模板-编译-挂载之前,Compile,此时-> 
        this.log('beforeMount')
        // 输出 -- beforeMount --
        // 输出 this.msg = vue
        // 输出 this.$el =
        // 输出 undefined
    },
    mounted() {
        //模板挂载之后,此时$el已经有dom节点值
        this.log('mounted')
        // 输出 -- mounted --
        // 输出 this.msg = vue
        // 输出 this.$el =
        // 输出 dom节点
        this.msg = 'hello'
        // 组件更新之前会调用beforeUpdate
        // 输出 -- beforeUpdate --
        // 输出 this.msg = vue
        // 输出 this.$el =
        // 输出 dom节点
        // -->
        // 组件更新之前会调用updated
        // 输出 -- updated --
        // 输出 this.msg = hello
        // 输出 this.$el =
        // 输出 dom节点
    },
    beforeUpdate() {
        this.log('beforeUpdate')
    },
    updated() {
        this.log('updated')
    },
    beforeDestory() {
        //组件销毁前调用
        this.log('beforeDestory')
    },
    destoryed() {
        //组件销毁后调用
        this.log('destoryed')
    },
    activated() {
        // 组件使用keep-alive,被激活时调用
        this.log('activated');
        // 输出 -- activated --
        // 输出 this.msg = hello
        // 输出 this.$el =
        // 输出 dom节点
    },
    deactivated() {
        //组件使用keep-alive,组件被移除时候调用
        this.log('deactivated');
        // 输出 -- deactivated --
        // 输出 this.msg = hello
        // 输出 this.$el =
        // 输出 dom节点
    },
    methods:{
        log(str){
            console.log(`-- ${str} --`)
            console.log(`this.msg = ${this.msg}`);
            console.log(`this.$el = `);
            console.log(this.$el)
        }
    }
}
</script>

生命周期简化图

生命周期使用

  • created 实例创建完成后调用,在此阶段完成了对数据的观测,但是尚未挂载,可以在此函数中初始化一些数据
  • mounted el挂载到实例上后调用,经常第一个业务逻辑的出发点
  • beforeDestroy 在实例销毁时候调用,可以在这事件中主动解绑一些监听事件