Vue3基础(十yi)___常用生命周期函数___setup___onMounted___onUpdated

对比vue2

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

setup

setup处于beforeCreate之前,beforeCreate和created都将使用setup代替,里面没有this指向,没有data,没有methods,组合Api最终编译为options Api。

onBeforeMount

onBeforeMount页面挂在之前;

onMounted

onMounted页面初始化完毕,一般进行ajax获取数据;

onBeforeUpdate

onBeforeUpdate页面进行更新之前;

onUpdated

onUpdated页面更新完成之后;

onBeforeUnmount

onBeforeUnmount页面销毁之前;

onUnmounted

onUnmounted页面销毁;

首先下载vue-router 我们在进行页面跳转的时候会使用到;
Vue3基础(十yi)___常用生命周期函数___setup___onMounted___onUpdated_第1张图片
在main中进行挂载全局 router

import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import { createRouter, createWebHashHistory } from 'vue-router'
const HelloWorld = () => import("./components/HelloWorld.vue")
const home = () => import("./components/home.vue")
const router = createRouter({
    history: createWebHashHistory(),
    routes: [
    { path: '/hellow', component: HelloWorld }, 
    { path: '/', component: home}
    ],
})
createApp(App).use(router).mount('#app')

/home

<template>
  <div>
    <p>age:{{ strObj.age }}</p>
    <button @click="changeAgeFun">changeAgeFun按钮</button>
    <button @click="goHellowPages">跳转到hellow页面</button>
  </div>
</template>

<script>
import {
  ref,
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
} from "vue";
import { useRouter } from "vue-router";
export default {
  name: "App",
  setup() {
    let strObj = ref({ age: 18 });
    onBeforeMount(() => {
      console.log("onBeforeMount===");
    });
    onMounted(() => {
      console.log("onMounted===");
    });
    onBeforeUpdate(() => {
      console.log("onBeforeUpdate===");
    });
    onUpdated(() => {
      console.log("onUpdated===");
    });
    onBeforeUnmount(() => {
      console.log("onBeforeUnmount===");
    });
    onUnmounted(() => {
      console.log("onUnmounted===");
    });
    const changeAgeFun = () => {
      strObj.value.age++;
      console.log("年龄进行加,页面发生改变===");
    };
    const router = useRouter();
    const goHellowPages = () => {
      console.log("进行路由跳转===");
      router.push("/hellow");
    };
    return { strObj, changeAgeFun, goHellowPages };
  },
};
</script>

/hellow

<template>
  <h1>我是hellow组件</h1>
</template>
<script>
export default {
}
</script>

首先点击改变年龄按钮,让年龄改变,出发页面的更新,随后进行页面的跳转,销毁当前实例
Vue3基础(十yi)___常用生命周期函数___setup___onMounted___onUpdated_第2张图片

你可能感兴趣的:(#,vue,#,js,vue,javascript,es6,vue.js,html5)