全部学科
Python全栈
python
NodeJS全栈
nodejs
📅 2026-05-20 5 分钟 ✍️ juanwangdev

beforeDestroy与destroyed

这两个钩子处理组件销毁阶段的逻辑。

Vue 2 命名

JavaScript
export default {
  beforeDestroy() {
    // 组件仍可用
    clearInterval(this.timer)
  },
  destroyed() {
    // 组件已销毁
    console.log('组件已销毁')
  }
}

Vue 3 命名

JavaScript
export default {
  beforeUnmount() {
    clearInterval(this.timer)
  },
  unmounted() {
    console.log('组件已卸载')
  }
}

Composition API

JavaScript
import { onBeforeUnmount, onUnmounted } from 'vue'

export default {
  setup() {
    const timer = setInterval(() => {
      console.log('tick')
    }, 1000)
    
    onBeforeUnmount(() => {
      clearInterval(timer)
    })
    
    onUnmounted(() => {
      console.log('清理完成')
    })
  }
}

典型清理

JavaScript
onUnmounted(() => {
  // 清理定时器
  clearInterval(timer)
  
  // 移除事件监听
  window.removeEventListener('resize', handler)
  
  // 取消订阅
  subscription.unsubscribe()
})

要点总结

  • beforeDestroy/beforeUnmount 在销毁前执行
  • destroyed/unmounted 在销毁后执行
  • Vue 3 将命名改为 Unmount 系列
  • 用于清理定时器、事件监听、订阅等资源
想在手机上练习这篇文章的配套题目?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码
← 上一篇 beforeUpdate与updated
下一篇 → activated与deactivated
扫码体验小程序
加载中
想在手机上刷题学习?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码