Vue3.0商店后台管理系统项目实战-生命周期

2022-10-12  本文已影响0人  祈澈菇凉

vue2的8个生命周期和vue3对应的8个生命周期

1:onBeforeMount

onMounted

<template>
  <div class="about">
    <h1>vue3的生命周期</h1>
    <div id="dom">{{msg}}</div>
  </div>
</template>

<script>
import { reactive, toRefs, onBeforeMount, onMounted } from "vue";

export default ({
  setup() {
    const data = reactive({
      msg: "你好",
    });

    //数据渲染前
    onBeforeMount(() => {
      console.log("onBeforeMount",document.querySelector("#dom"))
    });
  //数据渲染后
    onMounted(() => {
       console.log("onMounted",document.querySelector("#dom"))
    });


    

    return {
      ...toRefs(data),
    };
  },
});
</script>


2:onBeforeUpdate,onUpdated
dom更新前和dom更新后
2s过后,触发onBeforeUpdate,onUpdated

<template>
  <div class="about">
    <h1>vue3的生命周期</h1>
    <div id="dom">{{ msg }}</div>
  </div>
</template>

<script>
import {
  reactive,
  toRefs,
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
} from "vue";

export default {
  setup() {
    const data = reactive({
      msg: "你好",
    });

    //数据渲染前
    onBeforeMount(() => {
      console.log("onBeforeMount", document.querySelector("#dom"));
    });

    //数据渲染后
    onMounted(() => {
      console.log("onMounted", document.querySelector("#dom"));
      setTimeout(() => {
        data.msg = "hello";
      }, 2000);
    });

    //dom更新前
    onBeforeUpdate(() => {
      console.log("onBeforeUpdate", document.querySelector("#dom"));
    });

    //dom更新后
    onUpdated(() => {
      console.log("onUpdated", document.querySelector("#dom"));
    });

    return {
      ...toRefs(data),
    };
  },
};
</script>


上一篇下一篇

猜你喜欢

热点阅读