025、Vue3+TypeScript基础,使用组合式API时组件的生命周期
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、浏览器效果图:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步