卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章75203本站已运行4311

vue3怎么写组件卸载

在 vue 3 中,可以通过两种方式卸载组件:(1) 使用 beforeunmount 生命周期钩子,在组件卸载前执行清理操作;(2) 使用 ismounted 属性,在组件卸载后执行任何操作。

vue3怎么写组件卸载

Vue 3 中卸载组件

在 Vue 3 中,有两种主要方法可以卸载组件。

方法 1:使用 beforeUnmount 生命周期钩子

beforeUnmount 生命周期钩子在组件即将卸载时触发。你可以使用它来执行任何必要的清理操作,例如:

立即学习“前端免费学习笔记(深入)”;

// MyComponent.vue
export default {
  beforeUnmount() {
    // 清理任何挂载的监听器、定时器或订阅
    this.someListener.remove()
    clearInterval(this.someTimer)
    this.someSubscription.unsubscribe()
  }
}

方法 2:使用 isMounted 属性

isMounted 属性是一个内置的 Vue 属性,它在组件被卸载后变为 false。你可以使用它来在组件卸载时执行任何操作:

// MyComponent.vue
export default {
  data() {
    return {
      isMounted: true
    }
  },
  unmounted() {
    // 清理任何挂载的监听器、定时器或订阅
    this.someListener.remove()
    clearInterval(this.someTimer)
    this.someSubscription.unsubscribe()
  },
  // 仅在组件被挂载时执行
  mounted() {
    this.someListener = this.$el.addEventListener(...)
    this.someTimer = setInterval(...)
    this.someSubscription = this.$store.subscribe(...)
  }
}
卓越飞翔博客
上一篇: vue3怎么用ref
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏