Vue 生命周期

一、什么是生命周期?

Vue 实例从创建到销毁的过程,就是生命周期。

二、生命周期钩子

1、创建期间的生命周期函数:

  • beforeCreate:实例刚在内存中被创建出来,此时还没初始化好 data 和 methods 属性
  • created:实例已在内存中创建,此时 data 和 methods 已经创建完成,还没开始编译模板
  • beforeMount:此时已经完成了模板的编译,但还没挂载到页面中
  • mounted:此时已将编译好的模板挂载到页面指定的容器中显示

 

2、运行期间的生命周期函数:

  • beforeUpdate:状态更新之前执行此函数,此时 data 中的状态值是最新的,但界面上显示的数据还是旧的,因为还没开始重新渲染 DOM 节点
  • updated:实例更新完之后调用此函数,此时 data 中的状态值和界面上显示的数据都已经完成了更新,界面已被重新渲染好

 

3、销毁期间的生命周期函数:

  • beforeDestroy:实例销毁之前调用,这里实例仍然完全可用
  • destroyed:Vue 实例销毁后调用,调用后 Vue 实例指示的所有东西都会解绑,所有的事件监听器会被移除,所有的子实例也会被销毁

三、生命周期图示

四、代码示例

new Vue({
    data: {
        message: 0
    },
    template: '<div>{{ message }}</div>',
    beforeCreate() {
        console.log(this.$el, 'beforeCreate');
    },
    created() {
        console.log(this.$el, 'created');
    },
    beforeMount() {
        console.log(this.$el, 'beforeMount');
    },
    mounted() {
        console.log(this.$el, 'mounted');
    },
    beforeUpdate() {
        console.log(this.$el, 'beforeUpdate');
    },
    updated() {
        console.log(this.$el, 'updated');
    },
    activated() {
        console.log(this.$el, 'activated');
    },
    deactivated() {
        console.log(this.$el, 'deactivated');
    },
    beforeDestroy() {
        console.log(this.$el, 'beforeDestroy');
    },
    destroyed() {
        console.log(this.$el, 'destroyed');
    },
    errorCaptured() {
        console.log(this.$el, 'errorCaptured');
    }
});

// 输出结果

这里,beforeCreate() 和 created() 两个生命周期方法依次被执行,而其它生命周期方法没被触发执行。

如果加上 el 属性

new Vue({
    el: '#app', // 设置 el 属性
    // ...
});

或调用 vm.$mount() 方法

var app = new Vue({
    // ...
});

app.$mount('#root'); // 调用 Vue 实例的 $mount() 方法

则输出结果为:

可以看到 beforeCreate()、created()、beforeMount() 和 mounted() 四个生命周期方法依次被执行。

因此,在 new 一个 Vue 实例时,如果没设置 el 属性或调用 Vue 实例的 $mount() 方法,其实只会执行 beforeCreate() 和 created() 方法,原因在于生命周期中的 mounted() 方法把 Vue 实例中的 template 属性里的 html 挂载到 el 属性对应的 dom 节点上,如果没有定义 el 属性或没调用 Vue 实例的 $mount() 方法,就无法执行挂载的动作,因为不知要挂载到哪去

原文地址:https://www.cnblogs.com/Leophen/p/11247668.html