Custom Directives: Element Lifecycle Hooks (created, mounted, updated, unmounted)
- Last updated
- Prerequisites:
- Vue Template Directives
- DOM element manipulation
- vue
- directives
- dom
- lifecycle
- mounted
- v-custom
Read at your depth
The practical view
Custom directives provide low-level DOM access on plain elements. Define a directive object with lifecycle hooks: `created`, `beforeMount`, `mounted`, `beforeUpdate`, `updated`, `beforeUnmount`, `unmounted`. Inside a hook (e.g. `mounted(el, binding)`), `el` is the raw DOM element and `binding.value` contains the evaluated expression. Register globally with `app.directive('name', ...)` or locally in `<script setup>` with `const vFocus = { mounted: (el) => el.focus() }`.
The same idea in other frameworks
Custom hooks using `useRef` + `useEffect` DOM element attachment.Angular `@Directive()` with `ElementRef` and lifecycle hooks (`ngOnInit`, `ngOnDestroy`).Custom directive object with `mounted(el, binding)` and `unmounted(el)`.Svelte `use:action` returning `{ update, destroy }`.Legacy vs modern
Template Ref Boilerplate vs Reusable Custom Directive
Managing element focus via template refs in every component is repetitive; a `v-focus` directive makes it declarative.
const inputRef = ref(null); onMounted(() => inputRef.value.focus()); // ❌ Repeated per componentconst vFocus = { mounted: (el) => el.focus() }; // ✅ NEW: Declarative and reusableInterview gotchas
Context
Interviewers test your migration knowledge and framework lifecycle comprehension.
The mechanical answer
Vue 2 used `bind`, `inserted`, `update`, `componentUpdated`, and `unbind`. Vue 3 renamed these hooks to align directly with Vue component lifecycles: `created`, `beforeMount`, `mounted` (replaces `inserted`), `beforeUpdate`, `updated` (replaces `componentUpdated`), `beforeUnmount`, and `unmounted` (replaces `unbind`).
Trap
Using `inserted` in Vue 3 will fail silently as the hook is never invoked.
Context
Checks awareness of isomorphic rendering limitations with DOM directives.
The mechanical answer
Custom directives manipulate the physical DOM (`el.focus()`, `el.addEventListener()`). Because the server has no real DOM environment, custom directives will throw errors or have no effect during SSR unless a custom server directive transform (`getSSRProps`) is provided to convert directive values into static HTML attributes.
Trap
If a directive only needs to attach event listeners or styles, prefer standard Vue template attributes or components when building SSR/Nuxt applications.