【vue3入门】-【22】 组件生命周期
组件生命周期
每个Vue组件实例在创建是都需要经历一系列的初始化步骤,比如设置好数据侦听,编译模版,挂载实例到DOM,以及在数据改变时更新DOM。在此过程中,它也会运行被称为生命周期钩子的函数,让开发者有机会在特定阶段运行自己的代码。
生命周期函数都是会自己执行
app.vue
<template>
<h3>组件的生命周期</h3>
<p>{{ message }}</p>
<button @click="UpdateMessage">更新</button>
</template>
<script>
/**
* 生命周期函数:
* 创建期:beforeCreate created
* 挂载期:beforeMounte mounted
* 更新期:beforeUpdate updated
* 销毁期:beforeUmounted unmounted
*/
export default{
beforeCreate(){
console.log("组件创建之前");
},
created(){
console.log("组件创建之后");
},
beforeMount(){
console.log("组件渲染之前");
},
mounted(){
console.log("组件渲染之后");
},
beforeUpdate(){
console.log("组件更新之前");
},
updated(){
console.log("组件更新之后");
},
beforeUnmount(){
console.log("组件销毁之前");
},
unmounted(){
console.log("组件销毁之后");
},
data(){
return{
message:"手动更新之前"
}
},
methods:{
UpdateMessage(){
this.message = "手动更新后"
}
}
}
</script>
生命周期应用
组件的生命周期会随着我们对vue的了解越多,也会越来越重要,这里我们先讲两个常用的应用
- 通过ref获取元素DOM结构
- 模拟网络请求渲染数据
通过ref获取元素DOM结构
UseComponent.vue
<template>
<h3>组件生命周期函数应用</h3>
<p ref="name">测试组件Use</p>
</template>
<script>
export default {
beforeMount() {
console.log(this.$refs.name); // 读取到的是undefined
},
mounted() {
console.log(this.$refs.name); // 读取到的是DOM元素
}
}
</script>
通过网络请求渲染数据
一般来说都是需要等结构出来之后才渲染数据
UseComponent.vue
<template>
<h3>组件生命周期函数应用</h3>
<p ref="name">测试组件Use</p>
<ul>
<li v-for="( item, index ) of banner" :key="index">
<h3>{{ item.title }}</h3>
<p>{{ item.content }}</p>
</li>
</ul>
</template>
<script>
export default {
data() {
return {
banner: []
}
},
created() {
// 模拟接口响应,组件创建完成后执行此函数
this.banner = [{
title: "test1",
content: "test1 content"
}, {
title: "test2",
content: "test1 content"
},
{
title: "test3",
content: "test1 content"
}]
},
beforeMount() {
console.log(this.$refs.name); // 读取到的是undefined
},
mounted() {
// 组件挂载完成后,已经渲染完成DOM元素,(最常用),先渲染结构,再渲染数据
console.log(this.$refs.name); // 读取到的是DOM元素
}
}
</script>
以上内容出自
【【2023最新版】Vue3从入门到精通,零基础小白也能听得懂,写得出,web前端快速入门教程】 https://www.bilibili.com/video/BV1Rs4y127j8/?share_source=copy_web&vd_source=94c3d5330a46438059359e8dd2494fe9
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端