iT邦幫忙

2021 iThome 鐵人賽

DAY 13
0
Modern Web

別再說我不會框架,網頁 Vue 起來!系列 第 13

[Part 5 ] Vue.js 的精隨-元件生命週期 (序)

  • 分享至 

  • twitterImage
  •  

生命週期 ?

Vue.js 實體的一生: 建立 --> 更新 --> 銷毀

Vue Lifecycle Hooks

圖取自 A Complete Guide to Vue Lifecycle Hooks – with Vue 3 Updates

生命週期的事件可以拆成兩個 hooks (callback function),事件前 & 事件後!

主要有 4 個主要的事件可以使用 (等同於 8 個 hooks ):

  • Creation 建立元件
  • Mounting 掛載 DOM
  • Updates 資料被更新
  • Destruction 元件摧毀

Diagram of the Vue lifecycle, divided into four phases.

取自Vue.js in Action


怎麼用

這些在生命週期相關階段的 function (hooks),可以當做 option 在 Vue 實體中使用。
ex:

<script>     
   export default {         
      mounted() {             
         console.log('mounted!')         
      },         
      updated() {             
         console.log('updated!')         
      }     
   }
</script>

若使用 Vue 3 可以透過 Composition API,import hooks 到專案中就可以使用。
ex:

<script>
import { onMounted } from 'vue'

// 完整
//import {
//  onBeforeMount,
//  onMounted,
//  onBeforeUpdate,
//  onUpdated,
//  onBeforeUnmount,
//  onUnmounted,
//  onActivated,
//  onDeactivated,
//  onErrorCaptured
//} from "vue";

export default {
   setup () {
   // 寫在setup()中
     onMounted(() => {
       console.log('mounted in the composition api!')
     })
   }
}
</script>

對照表:

Options API Composition API (寫在setup()中)
beforeCreate 不需要
created 不需要
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeUnmount onBeforeUnmount
unmounted onUnmounted
errorCaptured onErrorCaptured
renderTracked onRenderTracked
renderTriggered onRenderTriggered
activated onActivated
deactivated onDeactivated

參考

A Complete Guide to Vue Lifecycle Hooks – with Vue 3 Updates


下篇預告

  • 生命週期

每日一句:
還好家目錄回來了 /images/emoticon/emoticon02.gif


上一篇
[Part 4 ] Vue.js 的精隨-元件 Slots
下一篇
[Part 6 ] Vue.js 的精隨-元件生命週期 (續)
系列文
別再說我不會框架,網頁 Vue 起來!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言