Skip to main content

What are Vue directives?

Vue directives are special attributes in a template that let you "bind" logic to DOM elements and control their behavior. They always start with the v- prefix.

In other words: directives are a way to tell Vue what to do with an element in the template.


Standard Vue directives

Here are the most common ones:

DirectiveWhat it does
v-bindBinds a value to attributes (dynamic attributes)
v-modelTwo-way data binding
v-if / v-else / v-else-ifConditional rendering
v-showShows/hides via CSS display
v-forA loop for lists
v-on (@)Event binding
v-slotWorking with slots in components
v-htmlInserts HTML (dangerous!)

A simple example

javascript
<div id="app"> <p v-if="isVisible">Hello!</p> <input v-model="message" /> <button @click="toggle">Show/hide</button> <p v-bind:title="message"> Hover over me - you'll see message </p> </div>
javascript
const app = Vue.createApp({ data() { return { isVisible: true, message: "Hello Vue" } }, methods: { toggle() { this.isVisible = !this.isVisible; } } }).mount('#app');

Why are custom directives needed?

Vue provides a basic set, but sometimes you need to manipulate the DOM manually:

  • auto-focusing an input field;
  • input masks (for example, a phone number);
  • animations;
  • working with external libraries (for example, a tooltip, drag&drop).

Custom directives are created for this.

Example of a custom v-focus directive

javascript
const app = Vue.createApp({}); app.directive('focus', { mounted(el) { el.focus(); } });

And its usage:

javascript
<input v-focus />

Directive lifecycle (Vue 3)

A custom directive has these hooks:

HookWhen it's called
createdwhen the directive is created
beforeMountbefore mounting into the DOM
mountedafter it's inserted into the DOM
beforeUpdatebefore the VDOM updates
updatedafter it updates
beforeUnmountbefore it's removed
unmountedafter it's removed

Summary

Directives are Vue's mechanism for controlling the DOM. They let you:

  • bind data to attributes,
  • listen to events,
  • show/hide elements,
  • repeat elements as a list,
  • control input,
  • write your own DOM logic.

If asked in an interview, you can answer briefly:

"Directives are v- attributes that let you control the DOM in a template. Vue provides standard directives and lets you create custom ones for custom element behavior."

Short Answer

Interview ready
Premium

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