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、浏览器效果图:

 

posted @ 2024-08-18 15:44  像一棵海草海草海草  阅读(2)  评论(0编辑  收藏  举报