Vue3 life cycle hook function usage example, setup syntactic sugar mode

Vue3's lifecycle hook function, if you are capable, you can see the official example: Combined API: Lifecycle Hook | Vue.js

In the setup syntactic sugar mode, there will be two less hook functions: boforeCreated and created. These two functions are now equivalent to being replaced by setup, and it is enough to directly write logic in setup.

Here are six commonly used hook functions: onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted

Among them, onBeforeUnmount and onUnmounted need to refer to the component to implement the call, add it in the child component, and use v-if in the parent component to control the display and disappearance of the child component, that's it.

Subcomponent code:

<template>
<div>
这是关于页面的内容
</div>
</template>

<script setup lang='ts'>
import {onBeforeUnmount, onUnmounted } from 'vue'
// 组件销毁之前
onBeforeUnmount(() => {
  console.log("组件销毁之前");
})

// 组件销毁之后
onUnmounted(() => {
  console.log("组件销毁之后");
})
</script>

<style scoped>

</style>

Parent component code:

<template>
<div>
  <h2>Vue3的生命周期</h2>
  <div>
    <button @click="updateContent">点击更改组件内容</button>
    <button @click="show">创建和销毁组件</button>
    <div ref="demo">{
   
   { content }}</div>
    <AboutMe v-if="display" ></AboutMe>
  </div>
</div>
</template>

<script setup lang='ts'>
import { ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated } from 'vue'
// import AboutMe from './views/AboutMe.vue'
import AboutMe from './views/AboutMe.vue'

console.log("setup语法糖模式中,可以直接在这里当做created函数使用");

const demo = ref<HTMLDivElement>()

const content = ref<string>("这是内容:div内容")

const display = ref<boolean>(true)

const updateContent = ()=>{
  content.value = "div组价内容更新"
}

const show = ()=>{
  display.value = !display.value
}

// 页面渲染之前
onBeforeMount(() => {
  console.log("渲染之前", demo);
})

// 页面渲染之后
onMounted(() => {
  console.log("渲染之后", demo);
})

// 组件更新之前
onBeforeUpdate(() => {
  console.log("组件更新之前", demo);
})

// 组件更新之后
onUpdated(() => {
  console.log("组件更新之后", demo);
})

</script>

<style scoped>

</style>

Guess you like

Origin blog.csdn.net/weixin_44786530/article/details/130705883