一文詳解Vue選項式?API?的生命周期選項和組合式API
Vue2、Vue3 生命周期的變化
正好在看Vue的官方文檔,也正好比對一下,做一下筆記
選項式 API 的生命周期選項的變化
Vue2.x | Vue3 |
---|---|
beforeCreate | beforeCreate |
created | created |
beforeMount | beforeMount |
mounted | mounted |
beforeUpdate | beforeUpdate |
updated | updated |
beforeDestroy | beforeUnmount |
destroyed | unmounted |
新增 | |
errorCaptured | |
renderTracked | |
renderTriggered |
這里我們會發(fā)現(xiàn)Vue3對Vue2的生命周期鉤子似乎沒有做大的調(diào)整
- 修改
destroyed
生命周期選項被重命名為unmounted
beforeDestroy
生命周期選項被重命名為beforeUnmount
- 新增
- errorCaptured:在捕獲一個來自后代組件的錯誤時被調(diào)用。
- renderTracked:跟蹤虛擬 DOM 重新渲染時調(diào)用。
- renderTriggered:當(dāng)虛擬 DOM 重新渲染被觸發(fā)時調(diào)用。
小知識
所有生命周期鉤子的 this
上下文將自動綁定至當(dāng)前的實例中,所以我們可以在 鉤子函數(shù)中通過this
輕松訪問到 data、computed 和 methods。
那么我有個大膽的想法!就是用箭頭函數(shù)進行定義生命周期鉤子函數(shù),可以如期的訪問到我們想要的實例嗎?
測試:
const app = Vue.createApp({ data() { return { cart: 0 } }, mounted: () => { console.log(this.cart) }, methods: { addToCart() { this.cart += 1 } } }) app.mount("#app");
不出所望的undefined
了,我們打印一下this
指向的上下文是window
并不是我們的Vue
實例。
至于為什么會這樣,我們可以很簡單的從箭頭函數(shù)的特性來進行一波簡單的解釋:
我們在定義箭頭函數(shù)的時候,定義初就綁定了父級上下文,因為箭頭函數(shù)綁定了父級上下文,所以 this
不會指向預(yù)期的組件實例,并且this.data
、this.addToCart
都將會是 undefined。
組合式 生命周期選項 API
選項式 API 的生命周期選項和組合式 API 之間是有映射關(guān)系的, 整體來看,變化不大,只是名字大部分上是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 的生命周期的時候,發(fā)現(xiàn)了這個,說實話我在平常業(yè)務(wù)開發(fā)中還真沒怎么用過,不過秉承著寧可多學(xué)些也不錯過的就記錄一下吧!
Vue2x
在Vue2版本中,如果我們想要監(jiān)聽組件內(nèi)的生命周期的階段。我們可以通過 hook:${組件生命周期鉤子名稱}
來進行組件內(nèi)部的事件監(jiān)聽。
<template> <child-component @hook:updated="onUpdated"> </template>
Vue3x
在 Vue 3 中,如果我們想要監(jiān)聽組件內(nèi)的生命周期的階段。我們可以通過 vnode-${組件生命周期鉤子名稱}
來進行組件內(nèi)部的事件監(jiān)聽。額外地,這些事件現(xiàn)在也可用于 HTML 元素,和在組件上的用法一樣。
<template> <child-component @vnode-updated="onUpdated"> </template>
或者用駝峰命名法
<template> <child-component @vnodeUpdated="onUpdated"> </template>
以上就是一文詳解Vue選項式 API 的生命周期選項和組合式API的詳細內(nèi)容,更多關(guān)于Vue選項組合API生命周期的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Vue+thinkphp5.1+axios實現(xiàn)文件上傳
這篇文章主要為大家詳細介紹了Vue+thinkphp5.1+axios實現(xiàn)文件上傳,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-05-05Vux+Axios攔截器增加loading的問題及實現(xiàn)方法
這篇文章主要介紹了Vux+Axios攔截器增加loading的問題及實現(xiàn)方法,文中通過實例代碼介紹了vue中使用axios的相關(guān)知識,需要的朋友可以參考下2018-11-11