TExcelTAD
Home › Vue › Vue Directives

Vue Directives

A directive is a special HTML attribute that starts with v-. It tells Vue to do something with the element: show or hide it, repeat it, bind an attribute, listen for an event, and so on. Directives are how a Vue template becomes dynamic.

Anatomy of a directive

html
<button v-on:click.prevent="save">Save</button>
<!--    │    │     │        │
        │    │     │        └─ value: a JavaScript expression
        │    │     └─ modifier: a special tweak (.prevent, .once, …)
        │    └─ argument: which event / attribute
        └─ directive name -->

Not every directive uses all parts. v-if="ok" has only a value, v-on:click="go" has an argument and a value, and v-once has nothing at all.

The built-in directives

Directive Shorthand Purpose Lesson
v-bind : Bind an attribute to data v-bind
v-if / v-else-if / v-else Render an element only when a condition is true v-if
v-show Toggle visibility with CSS display v-show
v-for Repeat an element for every item of a list v-for
v-on @ Listen for events Events
v-model Two-way binding for form inputs v-model
v-text Set the element's text content Templates
v-html Set the element's inner HTML Templates
v-slot # Pass content into components Slots
v-once Render once, then never update Templates
v-pre Skip compilation, show {{ }} literally Templates
v-cloak Hide uncompiled template until Vue is ready Templates
v-memo Skip re-rendering unless values change (advanced) —

A tour in one example

The playground uses five directives at once. Read the template, predict what will happen, then click the buttons.

html · try it yourself
<style>
  .done { text-decoration: line-through; color: gray; }
</style>

<div id="app">
  <input v-model="newTask" placeholder="New task">
  <button v-on:click="addTask">Add</button>

  <ul>
    <li v-for="task in tasks" :class="{ done: task.done }" @click="task.done = !task.done">
      {{ task.text }}
    </li>
  </ul>

  <p v-if="tasks.length === 0">Nothing to do!</p>
  <p v-else>{{ tasks.length }} task(s). Click a task to mark it done.</p>
</div>

<script type="module">
  import { createApp } from 'vue';

  createApp({
    data() {
      return {
        newTask: '',
        tasks: [
          { text: 'Learn directives', done: false },
          { text: 'Drink water', done: true }
        ]
      };
    },
    methods: {
      addTask() {
        if (this.newTask.trim()) {
          this.tasks.push({ text: this.newTask.trim(), done: false });
          this.newTask = '';
        }
      }
    }
  }).mount('#app');
</script>
  • v-model keeps newTask and the input box in sync.
  • v-on:click (and its shorthand @click) runs code on click.
  • v-for creates one <li> per task.
  • :class (short for v-bind:class) adds the done class when task.done is true.
  • v-if / v-else choose between two paragraphs.

Directive values are JavaScript expressions

The value of a directive is a single JavaScript expression evaluated against the component's data. These are all valid:

html
<p v-if="age >= 18">Adult</p>
<span :title="'Hello, ' + name">hover me</span>
<button @click="count += 2">+2</button>
<div :style="{ width: progress * 100 + '%' }"></div>

Statements such as if (…) {} or let x = 1 are not allowed inside a directive value — move that logic into a method.

Dynamic arguments

The argument itself can come from data when you wrap it in square brackets.

html · try it yourself
<div id="app">
  <p>Bind to:
    <button @click="attr = 'title'">title</button>
    <button @click="attr = 'aria-label'">aria-label</button>
  </p>
  <button :[attr]="'Bound via ' + attr">Inspect me</button>
  <p>Currently binding <code>{{ attr }}</code>.</p>
  <button @click="show">Log the attributes</button>
</div>

<script type="module">
  import { createApp } from 'vue';

  createApp({
    data: () => ({ attr: 'title' }),
    methods: {
      show() {
        const btn = document.querySelectorAll('#app button')[2];
        console.log('title =', btn.getAttribute('title'));
        console.log('aria-label =', btn.getAttribute('aria-label'));
      }
    }
  }).mount('#app');
</script>

Note: When the template is written directly in the HTML page (as in these playgrounds), the browser lower-cases attribute names before Vue sees them. Keep dynamic argument names lowercase there: :[attr] works, :[attrName] would silently break.

Shorthands

Two directives are so common that they have one-character shorthands. Most Vue code uses them:

Long form Shorthand
v-bind:href="url" :href="url"
v-on:click="go" @click="go"
v-slot:header #header

Tip: Pick one style and stay consistent. The official style guide recommends always using the shorthands.

Test yourself

What prefix do all built-in Vue directives share?

  1. vue-
  2. data-
  3. v-
  4. @

In v-on:submit.prevent="send", what is .prevent?

  1. The argument
  2. A modifier
  3. The value
  4. A filter

Which of these is NOT allowed as a directive value?

  1. count + 1
  2. ok ? 'yes' : 'no'
  3. let x = 5
  4. items.length > 0