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

生命周期 ?

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


<<:  .NET、托管代码(managed code)、反射

>>:  Day 25 | Livewire 实作 购物网站(四): 结帐页面

关於 Weekly Updates

在创业的过程中常常会迷失自我 YC SUS 里面有个 Weekly Updates 的机制 要求创业...

DAY28 第一个完整程序练习,一台计算机!(三)

今天我们要来讲剩下的方法 public void time(View view){ if (reco...

[Day24] - 介绍 Svelte.js 如何使用

前几天我们有说明 Virtual Dom 如何实作 , 今天我们来介绍一个 反对 Virtual D...

Day 08 - Kbars

本篇重点 Kbars 介绍及属性说明 使用 Pandas 将 Kbars 资料转换为 DataFra...