<!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>