Vue.js course ยท Module 14: Directives & Plugins

Custom Directives - Basics

2 min read ยท
In this lesson5

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()

const app = createApp(App)

app.directive('focus', {
  mounted(el) {
    el.focus()
  }
})

Now you can use v-focus in any component:

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

Local Registration

In a component, you can register a directive locally:

<script setup>
const vHighlight = {
  mounted(el) {
    el.style.backgroundColor = '#00ff88'
    el.style.padding = '4px 8px'
    el.style.borderRadius = '4px'
  }
}
</script>

<template>
  <span v-highlight>Important text</span>
</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
app.directive('log', {
  mounted(el) {
    console.log('Element added to DOM:', el.tagName)
  },
  updated(el) {
    console.log('Element updated:', el.tagName)
  },
  unmounted(el) {
    console.log('Element removed:', el.tagName)
  }
})

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:

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

This is equivalent to:

app.directive('color', {
  mounted(el, binding) {
    el.style.color = binding.value
  },
  updated(el, binding) {
    el.style.color = binding.value
  }
})
Code for this lesson: App.vue
<script setup>
import { ref } from 'vue'

// Local v-focus directive
const vFocus = {
  mounted(el) {
    el.focus()
  }
}

// Local v-highlight directive
const vHighlight = {
  mounted(el, binding) {
    el.style.backgroundColor = binding.value || 'rgba(0, 255, 136, 0.15)'
    el.style.padding = '4px 8px'
    el.style.borderRadius = '4px'
  },
  updated(el, binding) {
    el.style.backgroundColor = binding.value || 'rgba(0, 255, 136, 0.15)'
  }
}

// Local v-color directive (shortened form)
const vColor = (el, binding) => {
  el.style.color = binding.value || '#00ff88'
}

const searchQuery = ref('')
const showPanel = ref(true)
</script>

<template>
  <div class="nova-lab">
    <h1>Custom Directives - Basics</h1>

    <section class="section">
      <h2>v-focus - Auto Focus</h2>
      <input
        v-focus
        v-model="searchQuery"
        placeholder="Enter station command..."
        class="input"
      />
      <p class="hint">This input gets focus automatically</p>
    </section>

    <section class="section">
      <h2>v-highlight - Highlighting</h2>
      <p v-highlight>Default highlight (green)</p>
      <p v-highlight="'rgba(0, 180, 216, 0.2)'">Cyan highlight</p>
      <p v-highlight="'rgba(231, 76, 60, 0.2)'">Red highlight</p>
    </section>

    <section class="section">
      <h2>v-color - Shortened form</h2>
      <p v-color="'#00ff88'">Green text</p>
      <p v-color="'#00b4d8'">Cyan text</p>
      <p v-color="'#e74c3c'">Red text</p>
    </section>
  </div>
</template>

<style scoped>
.nova-lab {
  background: #0a0e27;
  color: #c0c0c0;
  min-height: 100vh;
  padding: 20px;
  font-family: monospace;
}
h1 { color: #00ff88; margin-bottom: 20px; }
h2 { color: #00b4d8; font-size: 16px; margin-bottom: 10px; }

.section {
  background: rgba(0, 180, 216, 0.05);
  border: 1px solid rgba(0, 180, 216, 0.2);
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 15px;
}

.input {
  background: rgba(0, 255, 136, 0.05);
  border: 1px solid #00ff88;
  color: #00ff88;
  padding: 10px 16px;
  border-radius: 6px;
  font-family: monospace;
  font-size: 14px;
  width: 100%;
  box-sizing: border-box;
}
.input:focus {
  outline: none;
  box-shadow: 0 0 8px rgba(0, 255, 136, 0.3);
}
.hint {
  color: #666;
  font-size: 12px;
  margin-top: 6px;
}
</style>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What are Custom Directives used for in Vue?

  2. 2. How do you register a directive globally in Vue?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Define a vFocus directive with a mounted hook and use it on an input.

  • Click in order

    Arrange the Custom Directive hooks in the order they are called:

  • Code editor

    Use the shorthand directive form (function instead of object) to set the text color.

  1. QuestionPurpose of Custom Directives
  2. QuestionGlobal directive registration
  3. Coding taskPractice: v-focus Directive
  4. QuestionThe mounted hook in a directive
  5. Click in orderOrder of directive hooks
  6. Coding taskPractice: v-color Directive

Useful articles