2026/4/18 3:27:03
网站建设
项目流程
网站建设印花税税率,海淀制作网站的公司,好大学网站设计,wordpress+的客户Vue3中unmounted钩子在组件销毁时触发#xff0c;常见场景包括#xff1a;v-if条件变化#xff1b;动态组件切换#xff1b;路由导航#xff1b;v-for列表更新#xff1b;父组件卸载#xff1b;手动调用unmount()#xff1b;Teleport目标移除#xff1b;组合式API停止…Vue3中unmounted钩子在组件销毁时触发常见场景包括v-if条件变化动态组件切换路由导航v-for列表更新父组件卸载手动调用unmount()Teleport目标移除组合式API停止响应式效果。KeepAlive缓存的组件会触发deactivated而非unmounted。最佳实践是在unmounted中清理定时器、事件监听等资源避免内存泄漏。理解这些触发条件有助于更好地管理组件生命周期。在 Vue 3 中unmounted生命周期钩子会在组件实例被销毁并从 DOM 中移除后调用。以下是会触发组件卸载unmount的常见情景1.条件渲染导致的组件移除vuetemplate ChildComponent v-ifshowChild / /template script setup import { ref } from vue const showChild ref(true) // 当 showChild 变为 false 时ChildComponent 会被卸载 setTimeout(() { showChild.value false // 触发 ChildComponent 的 unmount }, 3000) /script2.动态组件切换vuetemplate component :iscurrentComponent / /template script setup import { ref, shallowRef } from vue import ComponentA from ./ComponentA.vue import ComponentB from ./ComponentB.vue const currentComponent shallowRef(ComponentA) // 切换组件时前一个组件会被卸载 const switchComponent () { currentComponent.value ComponentB // ComponentA 会被卸载 } /script3.路由导航javascript// 路由导航时离开当前路由对应的组件会被卸载 router.push(/new-route) // 当前路由组件会被卸载如果不需要被缓存4.v-for 列表项变化vuetemplate div v-foritem in list :keyitem.id ListItem :itemitem / /div /template script setup import { ref } from vue const list ref([ { id: 1, name: Item 1 }, { id: 2, name: Item 2 } ]) // 移除数组元素时对应的组件会被卸载 const removeItem (id) { list.value list.value.filter(item item.id ! id) } /script5.父组件被卸载vuetemplate ParentComponent v-ifshowParent !-- 当 ParentComponent 被卸载时所有子组件也会被卸载 -- ChildComponent / /ParentComponent /template6.手动卸载组件vuetemplate div refcontainer/div /template script setup import { ref, onMounted, createApp } from vue import DynamicComponent from ./DynamicComponent.vue const container ref(null) let appInstance null onMounted(() { // 手动挂载组件 appInstance createApp(DynamicComponent) appInstance.mount(container.value) // 手动卸载组件 setTimeout(() { appInstance.unmount() // 触发 unmount container.value.innerHTML }, 5000) }) /script7.使用Teleport但目标元素被移除vuetemplate Teleport :totarget Modal / /Teleport /template script setup import { ref } from vue const target ref(body) // 如果目标元素被从 DOM 中移除通过 Teleport 传送的组件也会被卸载 /script8.在组合式 API 中手动停止响应式效果vuescript setup import { onUnmounted } from vue // 当组件被卸载时onUnmounted 钩子会被调用 onUnmounted(() { console.log(组件已卸载) // 清理工作如清除定时器、取消事件监听等 }) /script特殊情况组件不会被卸载使用KeepAlive缓存组件vuetemplate KeepAlive ComponentA v-ifshowA / ComponentB v-else / /KeepAlive /template组件切换时不会触发unmounted而是触发deactivated从缓存中移除时才会触发unmounted使用Suspense的异步组件异步组件的加载和卸载有特殊处理但最终卸载时仍会触发unmounted。最佳实践在unmounted或onUnmounted中清理定时器取消事件监听器清理第三方库实例取消网络请求清理全局状态监听vuescript setup import { onUnmounted } from vue let intervalId onMounted(() { intervalId setInterval(() { console.log(定时执行) }, 1000) }) onUnmounted(() { clearInterval(intervalId) // 清理定时器 }) /script理解这些触发情景有助于更好地管理组件生命周期和资源清理。