• 一个组件 创建 -> 运行 -> 销毁 的过程叫做生命周期

与Vue2生命周期的区别:

  • Vue3中可以继续使用Vue2的生命周期钩子,但是有两个更名了(卸载阶段)


    1. beforeDestory 改名为 beforeUnmount

    2. destoryed 改名为 unmounted

  • Vue3的setup()中集成了beforeCreatecreated两个生命周期钩子

  • 其他的跟以前一样,就是要在前面加一个on,并且需要引入才能使用

父组件

<template>
  <div class="App">
    <button @click="toggle">点击隐藏/显示Demo组件</button>
    <Demo v-if="isShow"></Demo>
  </div>
</template>
​
<script>
import Demo from '@/components/Demo.vue'
import { ref } from 'vue'
​
export default {
  name: 'App',
  components: {
    Demo,
  },
  setup() {
    let isShow = ref(true)
    function toggle() {
      isShow.value = !isShow.value
    }
    return {
      isShow,
      toggle,
    }
  },
}
</script>

子组件

<template>
  <div class="App">
    <p>PDD --- {
   { num }}</p>
    <button @click="reduce">砍一刀</button>
  </div>
</template>
​
<script>
import {
  onBeforeMount,
  onBeforeUnmount,
  onBeforeUpdate,
  onMounted,
  onUnmounted,
  onUpdated,
  ref,
} from 'vue'
​
export default {
  name: 'Demo',
  setup() {
    let num = ref(100)
    function reduce() {
      num.value--
    }
    // 创建阶段  beforeCreate 和 created 已经集成在setup()中了
    onBeforeMount(() => {
      console.log(1, 'onBeforeMount触发了')
    })
    onMounted(() => {
      console.log(2, 'onMounted触发了')
    })
    // 运行阶段
    onBeforeUpdate(() => {
      console.log(3, 'onBeforeUpdate触发了')
    })
    onUpdated(() => {
      console.log(4, 'onUpdated触发了')
    })
    // 卸载阶段
    onBeforeUnmount(() => {
      console.log(5, 'onBeforeUnmount触发了')
    })
    onUnmounted(() => {
      console.log(6, 'onUnmounted触发了')
    })
    return { num, reduce }
  },
}
</script>

原文链接:https://blog.csdn.net/qq_52845451/article/details/126680371

最后修改:2023 年 10 月 30 日
如果觉得我的文章对你有用,请随意赞赏