1、组件基础
每一个.vue 文件呢都可以充当组件来使用
每一个组件都可以复用
2、组件的生命周期
简单来说就是一个组件从创建到销毁的过程成为生命周期
在我们使用Vue3 组合式API 是没有 beforeCreate 和 created 这两个生命周期的
onBeforeMount()-创建之前
在组件DOM实际渲染安装之前调用。在这一步中,根元素还不存在。
onMounted()-创建完成
在组件的第一次渲染后调用,该元素现在可用,允许直接DOM访问
onBeforeUpdate()-更新之前
updated()-更新完成
onBeforeUnmount()-卸载之前
onUnmounted()-卸载完成
卸载组件实例后调用。调用此钩子时,组件实例的所有指令都被解除绑定,所有事件侦听器都被移除,所有子组件实例被卸载。
| 选项式 API | Hook inside setup |
|---|---|
| beforeCreate | Not needed* |
| created | Not needed* |
| beforeMount | onBeforeMount |
| mounted | onMounted |
| beforeUpdate | onBeforeUpdate更新之前 |
| updated | onUpdated更新之后 |
| beforeUnmount | onBeforeUnmount卸载之前 |
| unmounted | onUnmounted卸载完成 |
| errorCaptured | onErrorCaptured |
| renderTracked | onRenderTracked |
| renderTriggered | onRenderTriggered |
| activated | onActivated |
| deactivated | onDeactivated |
父组件
<script setup lang="ts">import { ref } from "vue";import HelloWorld from "./components/HelloWorld.vue";const flag = ref(true);</script><template><HelloWorld v-if="flag"></HelloWorld><div><button @click="flag = !flag">改变组件状态</button></div></template>
子组件
<script setup lang="ts">import {onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted,ref} from "vue";let count = ref(0)onBeforeMount(() => {let div = document.querySelector("#hello");console.log('创建之前 ===> onBeforeMount',div);});onMounted(() => {let div = document.querySelector("#hello");console.log('创建完成 ===> onMounted',div);});onBeforeUpdate(() => {console.log('更新之前 ===> onBeforeUpdate',count.value);})onUpdated(()=>{console.log('更新之后 ===> onUpdated',count.value);})onBeforeUnmount(()=>{console.log('卸载之前 ===> onBeforeUnmount');})onUnmounted(()=>{console.log('卸载完成 ===> onUnmounted');})</script><template><div id="hello">hello 胡雪</div>{{count}}<button @click="count++">+1</button></template>

