Life.vue:
<template>
<div>
<h2>{{msg}}</h2>
<button @click="Change()">改變msg</button>
</div>
</template>
<script>
// 生命周期函數/生命周期鉤子:組件掛載、以及組件更新、組件銷毀、的時候觸發的一系列的方法 這些方法就叫做生命周期函數
export default {
name: "life",
data(){
return {
msg:'這是一個生命周期測試組件',
}
},methods:{
Change(){
this.msg='我是改變值!'
}
},
//組件加載時:beforeCreate()、created()、 beforeMount()、mounted()
beforeCreate(){
console.log('實例創建之前');
},
created(){
console.log('實例創建完成');
},
beforeMount(){
console.log('模板編譯之前');
},
mounted(){//*
console.log('模板編譯完成');
},
//數據更新時:beforeUpdate()、updated()
beforeUpdate(){
console.log('數據更新之前');
},
updated(){
console.log('數據更新完畢');
},
//銷毀實例時: beforeDestroy()、destroyed()
beforeDestroy(){//*作用:頁面銷毀時需要保存一些數據,就可以利用(監聽)這個生命鉤子函數
console.log('實例銷毀之前');
},
destroyed(){
console.log('實例銷毀完成');
}
}
</script>
<style scoped>
</style>
App.vue:
<template>
<div id="app">
<h2>{{msg}}</h2>
<v-life v-if="is_show"></v-life>
<button @click="is_show=!is_show">掛載/卸載組件</button>
<router-view/>
</div>
</template>
步驟:
1、引入組件
2、掛在組件
3、在模板中使用
生命周期函數/生命周期鉤子:組件掛載、以及組件更新、組件銷毀、的時候觸發的一系列的方法 這些方法就叫做生命周期函數
<script>
import Life from './components/Life.vue';//1、引入組件
export default {
name: 'App',
data (){
return{
msg:'你好!',
is_show:true,
}
},
methods:{//用于放置自定義方法
},
components:{
'v-life':Life,//2、注冊組件
}
}
</script>
<style>
app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #2c3e50;
margin-top: 60px;
}
</style>
//組件加載、頁面更新時,觸發以下函數:
//數據更新時,觸發以下函數:
//組件銷毀時,觸發以下函數:
//組件再次加載時,觸發以下函數: