Vue directives are special attributes (v-if, v-for, v-model, v-bind, v-on) that apply reactive behavior to DOM elements. They control rendering, bind data, and handle events. Framework focus: Vue SFC patterns, ref/reactive state, computed/watch, and v-model bindings.
What are Vue directives and how do they work?
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
Overview
In Vue, directives are custom HTML attributes prefixed with v- that provide reactive behavior to DOM elements. They allow you to bind data, listen for events, show or hide elements, and apply dynamic logic directly in templates without writing manual JavaScript for DOM manipulation.
<template>
<div>
<p v-if="isVisible">This paragraph is conditionally rendered.</p>
<p v-bind:title="message">Hover to see the message.</p>
<button v-on:click="toggleVisibility">Toggle Visibility</button>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: true,
message: 'Hello from Vue!'
};
},
methods: {
toggleVisibility() {
this.isVisible = !this.isVisible;
}
}
};
</script>
In this example, three directives are used:
• v-if conditionally renders an element.
• v-bind dynamically binds a JavaScript value to an attribute.
• v-on listens for user events like clicks.
How Directives Work
When Vue compiles a template, it parses all directives and establishes reactivity links between the DOM and your component data. Whenever the underlying data changes, Vue automatically updates the DOM to reflect the new state — no manual DOM manipulation required.
Common Built-in Directives
Directive | Description |
|---|---|
v-if / v-else / v-else-if | Conditionally render elements based on a boolean expression. |
v-show | Toggles visibility using the CSS display property. |
v-for | Loops through arrays or objects to render lists. |
v-bind | Binds dynamic attributes or props to elements and components. |
v-on | Attaches event listeners to DOM elements. |
v-model | Creates two-way data binding with form inputs. |
v-html | Renders raw HTML content inside an element. |
v-text | Updates an element’s text content directly. |
Custom Directives
Vue also allows developers to define custom directives for specialized DOM behavior. Custom directives are registered using app.directive() in Vue 3.
app.directive('focus', {
mounted(el) {
el.focus();
}
});
Now, using v-focus in your template automatically focuses the element when mounted.
Think of directives as instructions for the DOM — they tell Vue what to do with elements when your data changes, keeping everything reactive and declarative.
Summary
- Directives in Vue start with the prefix
v-and enhance HTML behavior. - They dynamically bind data, handle events, and control the DOM.
- Vue provides built-in directives like
v-if,v-for,v-bind, andv-on. - You can create custom directives for advanced, reusable behavior.