Vue2 与 Vue3生命周期对比

Vue2 与 Vue3生命周期对比

1. Vue2.x
请添加图片描述


2. vu3.x

请添加图片描述
3. 与 2.x 版本生命周期相对应的组合式 API

  • beforeCreate -> 使用 setup()
  • created -> 使用 setup()
  • beforeMount -> onBeforeMount
  • mounted -> onMounted
  • beforeUpdate -> onBeforeUpdate
  • updated -> onUpdated
  • beforeDestroy -> onBeforeUnmount
  • destroyed -> onUnmounted
  • errorCaptured -> onErrorCaptured

4. 与 2.x 版本生命周期和 3.x 版本执行顺序

<template>
  <h1>父组件</h1>
  <button @click="isShow = !isShow">切换显示</button>
  <hr />
  <Child v-if="isShow" />
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";
import Child from "./components/child.vue";

export default defineComponent({
  name: "App",
  components: {
    Child,
  },
  setup() {
    const isShow = ref(true);
    return {
      isShow,
    };
  },
});
</script>
<template>
  <h1>子组件</h1>
  <h2>{{msg}}</h2>
  <button @click="updata">更新数据</button>
</template>

<script lang="ts">
import {
  defineComponent,
  onBeforeMount,
  onBeforeUnmount,
  onBeforeUpdate,
  onMounted,
  onUnmounted,
  onUpdated,
  ref,
} from "vue";

export default defineComponent({
  name: "Child",
  // vue2.x
  beforeCreate() {
    console.log("vu2.x - beforeCreate");
  },

  created() {
    console.log("vu2.x - created");
  },

  beforeMount() {
    console.log("vu2.x - beforeMount");
  },

  mounted() {
    console.log("vu2.x - mounted");
  },

  beforeUpdate() {
    console.log("vu2.x - beforeUpdate");
  },

  updated() {
    console.log("vu2.x - updated");
  },

  // vue3中无法使用 beforeDestroy、destroyed 

  // beforeDestroy() {
  //   console.log("vu2.x - beforeDestroy");
  // },

  // destroyed() {
  //   console.log("vu2.x - destroyed");
  // },

  // 修改成 beforeUnmount、unmounted
  beforeUnmount() {
    console.log("vu2.x - beforeUnmount");
  },

  unmounted() {
    console.log("vu2.x - unmounted");
  },

  setup() {  
    console.log("vu3.x - setup");
    
    const msg = ref("abc");

    const updata = () => {
      msg.value += "--";
    };

    onBeforeMount(() => {
      console.log("vue3.x - onBeforeMount");
    });

    onMounted(() => {
      console.log("vu3.x - onMounted");
    });

    onBeforeUpdate(() => {
      console.log("vu3.x - onBeforeUpdate");
    });

    onUpdated(() => {
      console.log("vu3.x - onUpdated");
    });

    onBeforeUnmount(() => {
      console.log("vu3.x - onBeforeUnmount");
    });

    onUnmounted(() => {
      console.log("vu3.x - onUnmounted");
    });

    return {
      msg,
      updata,
    };
  },
});
</script>

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值