全部学科
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 系列
  • 用于清理定时器、事件监听、订阅等资源

📝 发现内容有误?点击此处直接编辑

← 上一篇 beforeCreate与created
下一篇 → beforeMount与mounted
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库