Skip to main content

What is a directive?

Directive is a special attribute that adds behavior or logic to an element in a Vue template. It links the DOM and the component's reactive data, telling Vue what to do when the data changes.


1. Example of a simple directive

javascript
<template> <p v-if="isVisible">This text is shown when isVisible = true</p> </template> <script setup> import { ref } from 'vue' const isVisible = ref(true) </script>

Here v-if is a directive. It tells Vue: if isVisible is true, insert the element into the DOM, otherwise remove it.


2. General directive syntax

javascript
v-directive:argument.modifier="expression"
  • v-directive - the directive's name
  • :argument - an additional argument
  • .modifier - a refinement of behavior
  • "expression" - the value or logic the directive works with

Example:

javascript
<a v-bind:href="link" v-on:click.prevent="handleClick">Link</a>

Here:

  • v-bind:href="link" -> dynamically substitutes the value of link
  • v-on:click.prevent -> listens for a click and prevents the browser's default action

3. Core built-in Vue directives

DirectivePurpose
v-bind or :Binds a value to an element's attribute
v-on or @Binds an event handler
v-if, v-else, v-else-ifConditional rendering
v-showShows/hides an element via CSS (display: none)
v-forIterates over a list (like a loop)
v-modelTwo-way data binding (input ↔ state)
v-htmlInserts HTML as the element's content
v-textInserts text into the element
v-slotFor working with slots in components
v-pre, v-onceRender optimization (skip updating/skip compilation)

4. Example of using multiple directives

javascript
<template> <div v-if="user" v-bind:class="{ active: isActive }"> <p v-text="user.name"></p> <input v-model="user.email" /> <button @click="isActive = !isActive">Toggle active</button> </div> </template> <script setup> import { reactive, ref } from 'vue' const isActive = ref(false) const user = reactive({ name: 'Oleh', email: 'oleh@example.com' }) </script>

5. Custom directives

You can create your own directives when you need to control DOM behavior directly.

javascript
app.directive('focus', { mounted(el) { el.focus() } })
javascript
<input v-focus />

When the element mounts, Vue calls the mounted function and automatically sets focus on the input field.


Summary

A directive in Vue.js is a mechanism that adds reactive behavior to HTML elements.

It tells Vue how to update the DOM when the data changes.

There are built-in directives (v-if, v-for, v-bind, v-model, and others), and you can create your own for unique scenarios (such as autofocus, lazy-load, etc.).

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.