Trung BìnhVue.js iconVue.js

Lifecycle hooks trong Composition API?

Trong <script setup>, lifecycle hooks được import và dùng như functions:

javascript
import { onMounted, onUpdated, onUnmounted, onBeforeMount, onBeforeUpdate, onBeforeUnmount } from 'vue'

onMounted(() => { console.log('mounted') })
onUnmounted(() => { /* cleanup */ })

Mapping từ Options API (bao gồm Vue 2 → Vue 3): beforeCreate/created → code trong setup() chạy thay thế, mountedonMounted, updatedonUpdated, beforeUpdateonBeforeUpdate, unmountedonUnmounted, beforeMountonBeforeMount.

  • Vue 2: beforeDestroyonBeforeUnmount, destroyedonUnmounted.

Pitfall: onMounted trong SSR (Nuxt) không chạy server-side — dùng cho browser-only code.

Xem toàn bộ Vue.js cùng filter theo level & chủ đề con.

Mở danh sách Vue.js