10、Vue 生命周期钩子函数

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>
//组件加载、页面更新时,触发以下函数:


image.png

//数据更新时,触发以下函数:


image.png

//组件销毁时,触发以下函数:
image.png

//组件再次加载时,触发以下函数:
image.png

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。