Vue 3
Lifecycle Hooks
Register lifecycle callbacks as composable functions.
By EZ4Code Team
lifecyclehooks
Code
import {
onBeforeMount, onMounted,
onBeforeUpdate, onUpdated,
onBeforeUnmount, onUnmounted
} from "vue";
export function useLogger() {
onBeforeMount(() => console.log("beforeMount"));
onMounted(() => console.log("mounted"));
onBeforeUpdate(() => console.log("beforeUpdate"));
onUpdated(() => console.log("updated"));
onBeforeUnmount(() => console.log("beforeUnmount"));
onUnmounted(() => console.log("unmounted"));
}
// In a component:
// setup() {
// useLogger();
// }Explanation
Vue 3 exposes lifecycle hooks as on* functions that register callbacks during component creation. onMounted runs after the DOM is rendered, ideal for fetching data. onBeforeUnmount is the place to clean up timers, listeners, and subscriptions.
More Vue 3 Snippets
Single-File Component
Define a Vue 3 component with script setup, template, and scoped styles.
Composition API
Organize reactive state, computed, and lifecycle logic by feature.
Refs & Reactive
Choose between ref and reactive for reactive state.
Computed & Watch
Derive values with computed and react to changes with watch.
Props & Emits
Declare inputs and events, and implement v-model on a component.
Slots & Scoped Slots
Distribute content with default, named, and scoped slots.