一.生命周期的意义
只有了解了Vue的生命周期,才能在开发项目的时候判断什么时候该发生什么事件,即很好的控制页面。
二.生命周期的全部历程
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>my-project</title>
</head>
<body>
<div id="app">
<p>{{ str }}</p>
<h3>{{ count }}</h3>
<button @click="addCount">add</button>
<button @click="destroy">销毁</button>
</div>
<script src="./vue.js"></script>
<script>
new Vue({
el:'#app',
data:{
str:'hello world',
count:10
},
methods:{
addCount(){
this.count++
},
destroy(){
this.$destroy()
}
}
</body>
</html>
1.beforeCreate
//在实例初始化之后
beforeCreate(){
console.log('beforeCreate');//beforeCreate
console.log(this.$el);//undefined
console.log(this.$data);//undefined
},
2.created//在实例创建完成后被立即调用 //如果要调用methods中的方法 或者是操作data中的数据 最早只能在created中操作 created(){ console.log('created');//created console.log(this.$el);//undefined console.log(this.$data);//可以获取数据 },
3.beforeMount
//在挂载开始之前被调用
//执行时 页面中的元素 没有真正的替换过来 只是之前的一些模板
beforeMount(){
console.log('beforeMount');
console.log(this.$el);//
console.log(this.$data);//可以获取数据
},
4.mounted
//在挂载完成之后被调用
//表示内存中的模版 已经真实的挂载到页面中 用户可以看到渲染的页面
mounted(){
console.log('mounted');
console.log(this.$el);//
console.log(this.$data);//可以获取数据
},
5.beforeUpdate
/*
在数据更新时调用 (页面还未更新 只是数据更新了)
执行时 页面中显示的数据还是旧的 但是data中的数据是新的(页面和数据尚未同步)
*/
beforeUpdate(){
console.log('beforeUpdate');
console.log(this.$el);//
console.log(this.$data);//可以获取数据
console.log(document.querySelector('#app').innerHTML);//<p>hello world</p> <h3>10</h3> <button>add</button>
},
6.updated
//页面更新完成之后被调用 数据更新 导致虚拟dom重新渲染(页面和数据同步)
updated(){
console.log('updated');
console.log(this.$el);//
console.log(this.$data);//可以获取数据
console.log(document.querySelector('#app').innerHTML);//<p>hello world</p> <h3>11</h3> <button>add</button>
},
7.beforeDestroy
//在实例销毁之前调用 (在这一步,实例仍然完全可用)
beforeDestroy(){
console.log('beforeDestroy');
console.log(this.$el);//
console.log(this.$data);//可以获取数据
},
8.destroyed
//在实例销毁之后调用
destroyed(){
console.log('destroyed');
console.log(this.$el);//
console.log(this.$data);//可以获取数据
}
三.生命周期