理解VUE生命周期

918 阅读1分钟

每个 Vue 实例在被创建之前都要经过一系列的初始化过程。例如需要设置数据监听、编译模板、挂载实例到 DOM、在数据变化时更新 DOM 等。同时在这个过程中也会运行一些叫做生命周期钩子的函数,给予用户机会在一些特定的场景下添加他们自己的代码。

生命周期

Vue的生命周期分为8个阶段:

beforeCreate Vue实例创建前

created 创建后

beforeMount 载入前(在挂载开始之前被调用:相关的 render 函数首次被调用。该钩子在服务器端渲染期间不被调用。)

mounted 载入后(el 被新创建的 vm.$el替换,并挂载到实例上去之后调用该钩子。如果 root实例挂载了一个文档内元素,当 mounted 被调用时 vm.$el也在文档内。该钩子在服务器端渲染期间不被调用。)

beforeUpdate 数据更新前(数据更新时调用,发生在虚拟 DOM 重新渲染和打补丁之前。)

updated 数据更新后

beforeDestroy 销毁前

destroyed 销毁后

举个栗子

HTML:

<div id="app">
	{{test}}
	<button v-on:click='change'>change</button>
</div>

JS:

var myVue = new Vue({          
	el: "#app",          
	data: {
		test: "生命周期"        
	},  
	methods:{
		change:function(){
			this.test='changed'
		}
	},    
 	beforeCreate: function() {          
		console.log("创建VUE实例前")            
		console.log(this.test)            
		console.log(this.$el)          
	},         
	created: function() {
	    console.log("创建之后");            
		console.log(this.test)  
		console.log(this.$el)          
	},         
	beforeMount: function() {            
		console.log("mount之前")            
		console.log(this.test)            
		console.log(this.$el)          
	},          
	mounted: function() {            
		console.log("mount之后")            
		console.log(this.test)            
		console.log(this.$el)          
	},          
	beforeUpdate: function() {            
		console.log("数据更新前");            
		console.log(this.test)            
		console.log(this.$el)          
	},          
	updated: function() {            
		console.log("数据更新完成");            
		console.log(this.test);            
		console.log(this.$el)          
	},          
	beforeDestroy: function() {            
		console.log("销毁前");            
		console.log(this.test)            
		console.log(this.$el)            
	},          
	destroyed: function() {           
		console.log("已销毁");          
		console.log(this.test)          
		console.log(this.$el)          
	}   
});  

运行后,查看控制台, 得到这个:

运行后
beforeUpdateupdatedbeforeDestroydestroyed并没有执行,因为没有触发。beforeUpdateupdated 发生在数据更新时。点击change后,再查看控制台
发生数据更新时
也可以在控制台直接输入myVue.test='向死而生'回车执行
数据更新时