×
  • Web前端首页
  • VueJs
  • Vue基础知识:分享“选项式 API 的生命周期选项和组合式API”的应用

Vue基础知识:分享“选项式 API 的生命周期选项和组合式API”的应用

作者:Terry2023.03.27来源:Web前端之家浏览:1965评论:0
关键词:vuejs

Vue基础知识:分享“选项式 API 的生命周期选项和组合式API”的应用。

选项式 API 的生命周期选项的变化

Vue2.xVue3
beforeCreatebeforeCreate
createdcreated
beforeMountbeforeMount
mountedmounted
beforeUpdatebeforeUpdate
updatedupdated
beforeDestroybeforeUnmount
destroyedunmounted

新增

errorCaptured

renderTracked

renderTriggered

这里我们会发现Vue3对Vue2的生命周期钩子似乎没有做大的调整

  • 修改

    • destroyed 生命周期选项被重命名为 unmounted

    • beforeDestroy 生命周期选项被重命名为 beforeUnmount

  • 新增

    • errorCaptured:在捕获一个来自后代组件的错误时被调用。

    • renderTracked:跟踪虚拟 DOM 重新渲染时调用。

    • renderTriggered:当虚拟 DOM 重新渲染被触发时调用。

小知识

所有生命周期钩子的 this 上下文将自动绑定至当前的实例中,所以我们可以在 钩子函数中通过this轻松访问到 data、computed 和 methods。

那么我有个大胆的想法!就是用箭头函数进行定义生命周期钩子函数,可以如期的访问到我们想要的实例吗?

测试:

const app = Vue.createApp({
  data() {
    return {
      cart: 0
   }
},
mounted: () => { console.log(this.cart) },
  methods: {
    addToCart() {
      this.cart += 1
    }
  }
})

app.mount("#app");

不出所望的undefined了,我们打印一下this。

image.png

指向的上下文是window并不是我们的Vue实例。

至于为什么会这样,我们可以很简单的从箭头函数的特性来进行一波简单的解释:
我们在定义箭头函数的时候,定义初就绑定了父级上下文,因为箭头函数绑定了父级上下文,所以 this 不会指向预期的组件实例,并且this.datathis.addToCart 都将会是 undefined。

组合式 生命周期选项 API

选项式 API 的生命周期选项和组合式 API 之间是有映射关系的, 整体来看,变化不大,只是名字大部分上是on${选项式 API 的生命周期选项}

  • 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

使用:

export default {
  setup() {
    // mounted
    onMounted(() => {
      console.log('Component is mounted!')
    })
  }
}

VNode 生命周期事件

在查阅 Vue 的生命周期的时候,发现了这个,说实话我在平常业务开发中还真没怎么用过,不过秉承着宁可多学些也不错过的就记录一下吧!

Vue2x

在Vue2版本中,如果我们想要监听组件内的生命周期的阶段。我们可以通过 hook:${组件生命周期钩子名称}来进行组件内部的事件监听。

<template>
  <child-component @hook:updated="onUpdated">
</template>

或者用驼峰命名法

<template>
  <child-component @vnodeUpdated="onUpdated">
</template>

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/vuejs20230327.html

网友评论文明上网理性发言 已有0人参与

发表评论: