<template>
<div class="demo-container">
<h2>动态组件加载监控</h2>
<div class="status">当前组件状态:{{ componentStatus }}</div>
<div class="controls">
<button @click="loadComponent('ComponentA')">加载组件A</button>
<button @click="loadComponent('ComponentB')">加载组件B</button>
<button @click="unloadComponent">卸载组件</button>
</div>
<!-- 小李写的代码 -->
<component
:is="currentComponent"
v-if="currentComponent"
@vue:mounted="handleMounted"
@vue:updated="handleUpdated"
@vue:beforeUnmount="handleBeforeUnmount"
/>
</div>
</template>
<script setup>
import { ref } from 'vue'
const currentComponent = ref(null)
const componentStatus = ref('无组件')
const handleMounted = () => {
componentStatus.value = '✅ 组件已挂载'
console.log('组件挂载完成')
}
const handleUpdated = () => {
componentStatus.value = ' 组件已更新'
console.log('组件更新完成')
}
const handleBeforeUnmount = () => {
componentStatus.value = '❌ 组件即将卸载'
console.log('组件即将卸载')
}
const loadComponent = (name) => {
currentComponent.value = name
}
const unloadComponent = () => {
currentComponent.value = null
componentStatus.value = '无组件'
}
</script>
通过@vue方法实现对子组件内部更新销毁等功能的监听
最新推荐文章于 2025-08-05 22:11:48 发布