1. 生命周期图
这个是在官网上面的,每个Vue实例在被创建都要进过一系列的初始化过程,这个过程就是Vue生命周期
Vue提供的钩子函数
- beforeCreate ----- 初始化界面前
- created ----- 初始化界面后
- beforeMount ----- 渲染dom前
- mounted ----- 渲染dom后
- beforeUpdate ----- 更新数据前
- updated ----- 更新数据后
- beforeDestroy ----- 卸载数据前
- destroyed ----- 卸载数据后
Vue创建过程代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="app">
<father></father>
</div>
<script src="../vue.js"></script>
<script type="text/javascript">
var son = {
template: `
<div>
<div v-text="msg"></div>
<button @click='changeHandler'>改变</button>
</div>
`,
methods: {
changeHandler: function(){
this.msg = this.msg + '123';
}
},
data: function() {
return {
msg: 'abc'
}
},
beforeCreate: function(){
// 在new Vue()创建之前
console.log(this.msg); // undefined
},
created: function() {
// 这里一般是操作后台数据的数据响应式图
console.log(this.msg); // abc
},
beforeMount: function() {
// 挂载dom之前
console.log(document.getElementById('app'));
/*
<div id="app">
<vm></vm>
</div>
*/
},
mounted: function() {
// 挂载dom之后
console.log(document.getElementById('app'));
/*
<div id="app">
<div>abc</div>
<button>改变</button>
<button>销毁</button>
</div>
*/
},
beforeUpdate: function() {
// 在更新Dom之前调用此钩子函数应用: 可以获取原始dom
console.log(document.getElementById('app'));
},
updated: function() {
// 在更新Dom之后调用此钩子函数应用: 可以获取原始的dom
console.log(document.getElementById('app'));
},
beforeDestroy() {
console.log('beforeDestroy');
},
destroyed() {
console.log('destroyed');
},
activated() {
console.log('组件被激活了');
},
deactivated() {
console.log('组件被停用了');
}
}
var father = {
// keep-alive: 把son缓存到缓存里面
template: `
<div>
<keep-alive>
<son v-if="isBool"></son>
</keep-alive>
<button @click='change'>销毁</button>
</div>
`,
data: function(){
return{
isBool: true
}
},
methods: {
change: function() {
this.isBool = !this.isBool;
}
},
components:{
son,
},
}
new Vue({
el: '#app',
data(){
return {
}
},
components:{
father,
}
});
</script>
</body>
</html>
- 当点击改变的时候,会触发beforeUpdate钩子函数与updated钩子函数
- 点击销毁的时候
- 如果没有把son组件进行缓存就会进入beforeDestroy与destroyed钩子函数,然后在点击销毁就是创建,但是创建只会从最开始beforeCreate与creared开始触发
- 和上面代码一样son进行缓存了,就不会进入beforeDestroy与destroyed钩子函数而是进入activated与deactivated钩子函数,只会在缓存里面拿出来,激活组件和停用组件
组件被缓存的图
组件未被缓存的图