vue3快速入门-生命周期

此系列文章合集click me

此系列文章源码click me


对比表

Vue2对比Vue3执行阶段
beforeCreate==>setup()
created==>setup()组件创建之前
beforeMount==>onBeforeMount组件挂载到节点之前
mounted==>onMounted组件挂载完成后
beforeUpdate==>onBeforeUpdate组件更新之前
updated==>onUpdated组件更新完成之后
beforeDestroy==>onBeforeUnmount组件卸载之前
destroyed==>onUnmounted组件卸载完成
activated==>onActivated进入缓存组件时
deactivated==>onDeactivated离开缓存组件时
errorCaptured==>onErrorCaptured当子孙组件出错时
新增onRenderTriggered跟踪虚拟 DOM 重新渲染时调用
新增onRenderTracked当虚拟 DOM 重新渲染被触发时调用

lifeCycle.vue

<template>
  <div id="app">
    <h2>msg: {{ msg }}</h2>
    <button @click="updateMsg">更新msg</button>

    <button @click="goKeepAliveCom">前往缓存组件</button>
  </div>
</template>
<script lang="ts">
import {
  ref,
  defineComponent,
  onBeforeMount,
  onBeforeUnmount,
  onBeforeUpdate,
  onMounted,
  onUnmounted,
  onUpdated,
} from "vue";
import { useRouter } from "vue-router";

export default defineComponent({
  setup() {
    const msg = ref("温情");

    const updateMsg = () => {
      msg.value += "K";
    };

    const router = useRouter();

    const goKeepAliveCom = () => {
        router.push('/keepAlive');
    }

    onBeforeMount(() => {
      console.log("onBeforeMount-组件挂载到节点之前");
    });

    onMounted(() => {
      console.log("onMounted-组件挂载完成后");
    });

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

    onUpdated(() => {
      console.log("onUpdated-组件更新完成之后");
    });

    onBeforeUnmount(() => {
      console.log("onBeforeUnmount-组件卸载之前");
    });

    onUnmounted(() => {
      console.log("onUnmounted-组件卸载完成");
    });

    console.log("setup-开始创建组件之前");

    return {
      msg,
      updateMsg,
      goKeepAliveCom
    };
  },
});
</script>

keep-alive.vue

<template>
  <div id="app">
    <input type="text" v-model="ipt" />
    <br />
    <button @click="router.back()">返回</button>
  </div>
</template>
<script lang="ts">
import { defineComponent, onActivated, onDeactivated, onMounted, ref } from "vue";
import { useRouter } from "vue-router";

export default defineComponent({
  setup() {
    const ipt = ref("");

    const router = useRouter();

    onMounted(() => {
        console.warn("只有第一次进入缓存组件才触发onMounted")
    })

    onActivated(() => {
      console.log("进入缓存组件onActivated");
    });

    onDeactivated(() => {
      console.log("离开缓存组件onDeactivated");
    });

    return { ipt, router };
  },
});
</script>

由于输出的实在太多,截图不便于理解,所以建议自己动手试试。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

温情key

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值