1、App.vue程式碼如下:
<template> <div class="app"> <h2>App.Vue</h2> <Person v-if="isShow"/> <button @click="isShow =!isShow">點我切換</button> </div> </template> <script lang="ts" setup name="App"> // JS或TS import Person from './view/Person.vue'; import {onMounted, ref} from 'vue'; let isShow = ref(true); onMounted(() => { console.log('!!!App.vue主頁面的onMounted被執行!!!'); }) </script> <style scoped> .app { background-color: #ddd; box-shadow: 0 0 10px; border-radius: 10px; padding: 20px; } </style>
2、Person.vue程式碼如下:
<template> <div class="person"> <h2>當前數值為:{{ num }}</h2> <button @click="add">點我+1</button> </div> </template> <script lang="ts" name="Person001" setup> import {onBeforeMount, onBeforeUnmount, onBeforeUpdate, onMounted, onUnmounted, onUpdated, ref} from 'vue' const num = ref(0) function add() { num.value++ } //建立函式 console.log('setup,建立函式') onBeforeMount(() => { console.log('onBeforeMount,函式被執行') }) onMounted(() => { console.log('onMounted,函式被執行') }) onBeforeUpdate(() => { console.log('onBeforeUpdate,函式被執行') }) onUpdated(() => { console.log('onUpdated,函式被執行') }) onBeforeUnmount(() => { console.log('onBeforeUnmount,函式被執行') }) onUnmounted(() => { console.log('onUnmounted,函式被執行') }) </script> <style scoped> .person { background-color: #ddd; box-shadow: 0 0 10px; border-radius: 10px; padding: 20px; button { margin: 0 5px; } } </style>
3、效果如下:
4、瀏覽器效果圖: