0
点赞
收藏
分享

微信扫一扫

生命周期类方法

生命周期方法,通常叫做生命周期钩子,在配置式API中我们已经了解了具体的生命周期方法,在Composition API的setup方法里面同样有对应的生命周期方法,他们的对应关系如下所示:

beforeCreate -> 使用 setup()

created -> 使用 setup()

beforeMount -> onBeforeMount

mounted -> onMounted

beforeUpdate -> onBeforeUpdate

updated -> onUpdated

beforeUnmount -> onBeforeUnmount

unmounted -> onUnmounted

errorCaptured -> onErrorCaptured

renderTracked -> onRenderTracked

renderTriggered -> onRenderTriggered

activated -> onActivated

deactivated -> onDeactivated

由于setup方法在组件的beforeCreate和created之前执行,所以不在提供对应的钩子方法,这些生命周期钩子注册函数只能在setup方法内同步使用,因为它们依赖于内部的全局状态来定位当前活动的实例 (此时正在调用其setup的组件实例),在没有当前活动实例的情况下,调用它们将会出错。同时,在这些生命周期钩子内同步创建的侦听器和计算属性也会在组件卸载时自动删除,这点和配置式API式一致的。如示例代码所示。

const MyComponent = {
  setup() {
    Vue.onMounted(() => {
      console.log('mounted!')
    })
    Vue.onUpdated(() => {
      console.log('updated!')
    })
    Vue.onUnmounted(() => {
      console.log('unmounted!')
    })
  }
}

举报

相关推荐

0 条评论