Vue之组件的生命周期
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<button @click='isShow=!isShow'>改变组件的生死</button>
<keep-alive> <!--此标签用于使里面的组件缓存起,因此避免销毁,创建的过程,若想看见创建和销毁的过程,去掉该标签即可-->
<App v-if='isShow'/>
</keep-alive>
</div>
<script src="../node_modules/vue/dist/vue.js"></script>
<script>
/* 组件的生命周期的图示链接:https://cn.vuejs.org/images/lifecycle.png
以下是与组件生命周期相关的钩子函数
- beforeCreate
- created
- beforeMount
- mounted
- beforeUpdate
- updated
- activated
- deactivated
- beforeDestory
- destoryed
*/
var App = {
template: `<div>我是局部组件App
<button @click='isShow=!isShow'>更新DOM</button>
<p v-if='isShow'>我被改变了~</p>
</div>`,
data() {
return {
msg:'hi',
isShow: false
}
},
beforeCreate() {
// 在组件创建前调用
console.log('Before create, you can not get msg, msg is:', this.msg);
},
created() {
// 在组件创建后调用
console.log('After created, you can get msg, msg is:', this.msg)
},
beforeMount() {
// 挂载数据到DOM前调用,此时还没有渲染局部组件里面的数据
console.log(document.getElementById('app'));
},
mounted() {
// 挂载数据到DOM后调用,此时已经正常地渲染了局部组件
console.log(document.getElementById('app'));
},
beforeUpdate() {
// 在更新DOM之前,调用此钩子函数,可以获取原始的DOM
console.log('I am original DOM:',document.getElementById('app').innerHTML);
},
updated() {
// 在更新DOM后调用此钩子函数,可以获取最新的DOM
console.log('I am new DOM:',document.getElementById('app').innerHTML)
},
beforeDestroy(){
console.log('beforeDestroy');
},
destroyed(){
console.log('destroyed');
},
activated(){
console.log('组件被激活了');
},
deactivated(){
console.log('组件被停用了');
}
};
new Vue({
el: '#app',
template: ``,
data() {
return {
isShow: false
}
},
components: {
App
}
});
</script>
</body>
</html>
不积跬步,无以至千里;不积小流,无以成江海