每个 Vue 组件实例在创建时都需要经历一系列的初始化步骤,比如设置好数据侦听,编译模板,挂载实例到 DOM,以及在数据改变时更新 DOM。在此过程中,它也会运行被称为生命周期钩子的函数,让开发者有机会在特定阶段运行自己的代码。
export default {
name: 'app',
components: {
HelloWorld
},
data() {
return {
msg: "welcome to your vue app"
}
},
beforeCreate() {
console.log("beforeCreate",this.$el,this.$data,this.msg);
this.init();
},
created() {
console.log("created",this.$el,this.$data,this.msg);
this.init();
},
beforeMount() {
console.log("beforeMount",this.$el,this.$data,this.msg);
},
mounted() {
console.log("mounted",this.$el,this.$data,this.msg);
},
beforeUpdate() {
console.log("beforeUpdate",this.$el,this.$data,this.msg);
},
updated() {
console.log("updated",this.$el,this.$data,this.msg);
},
beforeDestroy() {
console.log("beforeDestroy",this.$el,this.$data,this.msg);
},
destroyed() {
console.log("destroyed",this.$el,this.$data,this.msg);
},
methods: {
init() {
console.error("i is methods init function")
}
},
}
1、beforeCreate
根据官方的图就能知道, 是发生在初始化实例之前、数据观测和事件配置之前调用的
2、created
实例创建完成,初始化数据响应式。实例已完成以下的配置:数据观测(data observer),属性和方法的运算, watch/event 事件回调。然而,挂载阶段还没开始,$el 属性目前不可见。
3、beforeMounted
挂载之前被调用。首先会判断对象是否有el选项,如果有的话就继续向下编译,没有el选项,就停止编译,也就是说会停止到当前的生命周期,直到有调用vm.$mount(el),才继续往下执行。
(1).如果vue实例对象中有template参数选项,则将其作为模板编译成render函数。
(2).如果没有template选项,则将外部HTML作为模板编译。
(3).可以看到template中的模板优先级要高于outer HTML的优先级。
4、mounted
el 被新创建的 vm.$el 替换,并挂载到实例上去之后调用该钩子。
(在mounted之前div中还是通过{{msg}}进行占位的,因为此时还有挂在到页面上,还是JavaScript中的虚拟DOM形式存在的。在mounted之后可以看到div中的内容发生了变化)
5、beforeUpdate updated
当vue发现data中的数据发生了改变,会触发对应组件的重新渲染,先后调用beforeUpdate和updated钩子函数。
6、 beforeDestory destoryed
beforeDestroy钩子函数在实例销毁之前调用。在这一步,实例仍然完全可用。
destroyed钩子函数在Vue 实例销毁后调用。调用后,Vue 实例指示的所有东西都会解绑定,所有的事件监听器会被移除,所有的子实例也会被销毁。