Vue生命周期你真的理解了吗?(必会面试题)

58 阅读2分钟

🧑‍💻Vue生命周期

文章目录

🔥1.1Vue生命周期都有哪些?
🔥生命周期执行时机
🔥beforeCreate在组件实例被创建之初、组件的属性⽣效之前被调用
🔥created在组件实例已创建完毕。此时属性也已绑定,但真实DOM还未⽣成,$el 还不可⽤
🔥beforeMount在组件挂载开始之前被调⽤。相关的 render 函数⾸次被调⽤
🔥mounted在 el 被新建的 vm.$el 替换并挂载到实例上之后被调用
🔥beforeUpdate在组件数据更新之前调⽤。发⽣在虚拟 DOM 打补丁之前
🔥 update在组件数据更新之后被调用
🔥 activited在组件被激活时调⽤(使用了 <keep-alive> 的情况下)
🔥 deactivated在组件被销毁时调⽤(使用了 <keep-alive> 的情况下)
🔥 beforeDestory在组件销毁前调⽤
🔥 destoryed在组件销毁后调⽤

代码详情

class Vue{
	constructor( options ){
		options.beforeCreate.call(this)
		this.$data = options.data;
		
		options.created.call(this)
		options.beforeMount.call(this)

		this.$el = document.querySelector(options.el);
		options.mounted.call(this)
	}
}
new Vue({
  el:"#app",
  data : {
  	str:'123'
  },
  beforeCreate(){
  	console.log('beforeCreate',this.$el , this.$data)
  },
  created(){
  	console.log('created',this.$el , this.$data)
  },
  beforeMount(){
  	console.log('beforeMount',this.$el , this.$data)
  },
  mounted(){
  	console.log('mounted',this.$el , this.$data)
  },
})
🔥1.2 一旦进入组件或者一旦进入页面,会执行哪些生命周期?
  1. beforeCreate
  2. created
  3. beforeMount
  4. mounted
🔥1.3 如果使用了keep-alive会多出来俩个生命周期
  1. activated
  2. deactivated
🔥1.4 如果使用了keep-alive第一次进入组件会执行5个生命周期
  1. beforeCreate
  2. created
  3. beforeMount
  4. mounted
  5. activated
🔥1.5 如果使用了keep-alive第二次或者第N次,每次都会执行一个生命周期

activated

🔥1.6 父子组件嵌套执行生命周期的顺序

🔥挂载阶段

  1. beforeCreate

  2. created

  3. beforeMount

    1. beforeCreate
    2. created
    3. beforeMount
    4. mounted
  4. mounted

🔥更新阶段

  1. beforeUpdate

    1. eforeUpdate
    2. updated
  2. updated

🔥销毁阶段

  1. beforeDestroy

    1. beforeDestroy
    2. destroyed
  2. destroyed