Custom Directives — Vue

A custom directive is a directive (a v- attribute) that you write yourself: an object of hooks, which are functions Vue calls at certain moments to touch the…

v-if, v-for, v-model: every v- attribute you've used so far was made by the Vue team. They're called directives, special attributes that tell Vue to do something to an element. You can make your own directives, too.

A custom directive is one you write yourself, such as v-focus or v-price. A custom directive touches the DOM element directly, at chosen moments. Picture the price stamp at Mrs. Sri's stall. Whatever paper gets stamped (a receipt, a label or the menu board) comes out with a neat "$15.00". The stamp doesn't care what the paper is: it works directly on that paper. But when the price goes up, the paper has to be stamped again. In Vue, the stamp is the custom directive, and the paper is the element that has that directive's attribute. Vue presses the stamp, at the moments you pick.

A first directive: v-focus

The "Search menu" box at Mrs. Sri's stall should be ready to type in as soon as the page shows. This is a v-focus directive for that box:

<!-- MenuSearch.vue -->
<script setup>
const vFocus = {
  mounted(el) {
    el.focus()
  },
}
</script>

<template>
  <input v-focus placeholder="Search menu" />
</template>

Hooks: when a directive is called

These are the hooks a directive can have, and when Vue calls each one:

Hook When it is called
created the element is created, before its attributes and listeners are applied
beforeMount right before the element goes into the page
mounted the element is in the page
beforeUpdate the component is about to re-render
updated the component has finished re-rendering
beforeUnmount right before the element is removed
unmounted the element has been removed, for example because v-if turned false

Now a v-price that has only mounted. toFixed(2) writes the number with two decimal places, for example 15 becomes 15.00:

const vPrice = {
  mounted(el, binding) {
    el.textContent = "$" + binding.value.toFixed(2)
  },
}

On the <p> below, v-price="total" makes binding.value hold total. The button adds to total:

<p v-price="total"></p>
<button @click="total += 15">Add Fried Rice</button>

total starts at 15. The button is clicked once, and total becomes 30. What do you think the <p> says now?

Event total Hooks that run <p> says, mounted only <p> says, mounted + updated
start 15 mounted $15.00 $15.00
Add Fried Rice 30 beforeUpdate, updated $15.00 $30.00
Add Fried Rice 45 beforeUpdate, updated $15.00 $45.00

mounted runs only once, when the element is first placed. So after the click the text stays $15.00 even though total is already 30, like a paper that isn't stamped again when the price goes up. So that the text changes too, add updated with the same body:

const vPrice = {
  mounted(el, binding) {
    el.textContent = "$" + binding.value.toFixed(2)
  },
  updated(el, binding) {
    el.textContent = "$" + binding.value.toFixed(2)
  },
}

Since mounted and updated often do the same thing, Vue has a short form: a directive written as a function is called on mounted and on updated.

const vPrice = (el, binding) => {
  el.textContent = "$" + binding.value.toFixed(2)
}

binding: value, argument, modifiers

Every hook's second parameter is binding: what the directive's attribute holds. For <p v-price:short.bold="total">, binding holds this:

Part What it holds
binding.value the result of the expression total, say 30
binding.oldValue the previous value, only in beforeUpdate and updated, say 15
binding.arg the text after the colon: "short"
binding.modifiers an object with each word after a dot: { bold: true }

Registering a directive

A directive put on a component's tag, say <MenuCard v-price="15" />, lands on that component's root element, like the attributes in the attribute inheritance lesson. If the component has two root elements, the directive is ignored. In development mode, the console writes [Vue warn]: Runtime directive used on component with non-element root node. The directives will not function as intended.

In the exercise editor

The exercise editor compiles the template in the browser. The vFocus naming trick (a variable with the v prefix becomes a directive) is only recognised by the build tool, the program that compiles .vue files before the app runs. So in the editor, const vFocus plus <input v-focus> does nothing. In development mode, the console writes [Vue warn]: Failed to resolve directive: focus. The Playground uses the production build, so no message appears at all. What works: write the component as an object with the directives option, then place it with <component :is>:

const vFocus = { mounted(el) { el.focus() } }
const vPrice = (el, binding) => {
  el.textContent = "$" + binding.value.toFixed(2)
}

const Stall = {
  directives: { focus: vFocus, price: vPrice },
  setup() {
    const total = ref(15)
    return { total }
  },
  template: `
    <div>
      <input v-focus placeholder="Search menu" />
      <p>Total: <span v-price="total"></span></p>
      <button @click="total += 15">Add Fried Rice</button>
    </div>
  `,
}

---template---
<component :is="Stall" />

When to use a directive

Use a custom directive only when you really need to touch the DOM element directly. Examples are giving focus, attaching a listener to document and removing it in unmounted, or watching when a menu photo becomes visible on the screen. If all you need is text derived from data, a plain function such as {{ formatPrice(total) }} or a computed is clearer. v-price in this lesson is an example to show hooks and binding at work.

⚠️ Directives that stay silent, go stale, or throw

TL;DR: A custom directive is a directive (a v- attribute) that you write yourself: an object of hooks, which are functions Vue calls at certain moments to touch the DOM element directly. mounted(el, binding) runs once the element el is placed, updated after the component re-renders, and unmounted after the element is removed. A directive with only mounted doesn't follow data changes. Add updated, or write the directive as a function, which is called on mounted and on updated. binding is what the attribute holds: binding.value is the expression's value, binding.arg the text after the colon, and binding.modifiers an object with each word after a dot. In <script setup>, the variable name must start with v (vFocus becomes v-focus). In a component written as an object, register the directive through the directives option, and globally through app.directive. In the exercise editor, use that directives option, then place the component with <component :is>. To just transform text, use a computed.

⚡ A first directive: v-focus

Write:

<!-- MenuSearch.vue -->
<script setup>
const vFocus = {
  mounted(el) {
    el.focus()
  },
}
</script>

<template>
  <input v-focus placeholder="Search menu" />
</template>

Meaning: A directive is a special Vue attribute that starts with v-, and a custom directive is one you write yourself. It's written as an object of hooks, which are functions Vue calls at certain moments. mounted is called once the element is in the page, and el is the real DOM element, here the <input>. el.focus() puts the cursor in that input. The name vFocus lets this directive be used as v-focus.

⚡ The name must start with v

Guess first: <script setup> has const focus = { mounted: (el) => el.focus() }, then <input v-focus />. Does the input get focus?

Never. The name must be vFocus. A variable whose name doesn't start with v and then a capital letter isn't recognised as a directive.

Meaning: In <script setup>, vFocus becomes v-focus, and vPrice becomes v-price.

⚡ mounted runs only once

Write:

const vPrice = {
  mounted(el, binding) {
    el.textContent = "$" + binding.value.toFixed(2)
  },
}
Guess first: <p v-price="total"> writes total as a price. total starts at 15, so it says $15.00. Then a button changes total to 30. What does the <p> say now?

Still $15.00. mounted runs only once, when the element is first placed.

Meaning: binding is what the directive's attribute holds, and binding.value is the value of the expression, here total. So that the text changes too, add an updated hook with the same body, or write the directive as a function, which is called on mounted and on updated.

What you will learn