We use cookies to enhance your experience on the site
CodeWorlds

Custom Directives - Basics

Welcome to the NOVA LAB Command Center! Year 2087 — the space station interfaces require precise control over DOM elements. Vue provides Custom Directives that allow you to directly manipulate elements at a lower level than templates.

What Are Custom Directives?

Vue has built-in directives:

v-if
,
v-for
,
v-model
,
v-show
. But you can also create your own! Custom Directives provide direct access to the DOM element — something you can't achieve with templates alone.

Directives are an excellent tool when you need:

  • automatic focus on an input
  • handling clicks outside an element
  • lazy-loading images
  • custom tooltips

Global Registration: app.directive()

1const app = createApp(App)
2
3app.directive('focus', {
4  mounted(el) {
5    el.focus()
6  }
7})

Now you can use

v-focus
in any component:

1<template>
2  <input v-focus placeholder="Auto-focus!" />
3</template>

Local Registration

In a component, you can register a directive locally:

1<script setup>
2const vHighlight = {
3  mounted(el) {
4    el.style.backgroundColor = '#00ff88'
5    el.style.padding = '4px 8px'
6    el.style.borderRadius = '4px'
7  }
8}
9</script>
10
11<template>
12  <span v-highlight>Important text</span>
13</template>

Important convention: In

<script setup>
, a local directive must have a name starting with
v
(e.g.,
vHighlight
), and in the template you use it as
v-highlight
(camelCase converted to kebab-case).

Directive Lifecycle Hooks

Directives have hooks similar to the component lifecycle:

  • created
    — before the element's attributes are bound
  • beforeMount
    — before the element is inserted into the DOM
  • mounted
    — the element is already in the DOM (most commonly used)
  • beforeUpdate
    — before the parent component is updated
  • updated
    — after the parent component is updated
  • beforeUnmount
    — before removal from the DOM
  • unmounted
    — element removed from the DOM
1app.directive('log', {
2  mounted(el) {
3    console.log('Element added to DOM:', el.tagName)
4  },
5  updated(el) {
6    console.log('Element updated:', el.tagName)
7  },
8  unmounted(el) {
9    console.log('Element removed:', el.tagName)
10  }
11})

Shorthand Directive Form

If you only need

mounted
and
updated
with the same logic, you can use the shorthand form — a function instead of an object:

1app.directive('color', (el, binding) => {
2  el.style.color = binding.value
3})

This is equivalent to:

1app.directive('color', {
2  mounted(el, binding) {
3    el.style.color = binding.value
4  },
5  updated(el, binding) {
6    el.style.color = binding.value
7  }
8})
Go to CodeWorlds