Under The Hood
frontend vue Vue 3.x

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

react equivalent
Custom hooks using `useRef` + `useEffect` DOM element attachment.

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.

before → after
Manual Template Ref Focus
const inputRef = ref(null); onMounted(() => inputRef.value.focus()); // ❌ Repeated per component
Reusable v-focus Directive
const vFocus = { mounted: (el) => el.focus() }; // ✅ NEW: Declarative and reusable

Interview 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.

Under The Hood — a multi-depth technical interview hub.

Third-party licenses Press ⌘ K to search.