【vue3入门】-【22】 组件生命周期

组件生命周期

每个Vue组件实例在创建是都需要经历一系列的初始化步骤,比如设置好数据侦听,编译模版,挂载实例到DOM,以及在数据改变时更新DOM。在此过程中,它也会运行被称为生命周期钩子的函数,让开发者有机会在特定阶段运行自己的代码。

生命周期函数都是会自己执行

image

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>

image

生命周期应用

组件的生命周期会随着我们对vue的了解越多,也会越来越重要,这里我们先讲两个常用的应用

  1. 通过ref获取元素DOM结构
  2. 模拟网络请求渲染数据

通过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

posted @ 2024-05-13 23:13  PyAj  阅读(12)  评论(0编辑  收藏  举报