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>
- A directive is an object of hooks, functions Vue calls at certain moments.
mountedis called once the element is in the page. elis the real DOM element, here the<input>.el.focus()puts the cursor there, so a customer can type "noodles" right away.- In
<script setup>, a variable whose name starts withvand then a capital letter can be used as a directive:vFocusbecomesv-focus,vPricebecomesv-price. Without that prefix, Vue doesn't recognise it. - The result is the same as the code
onMounted(() => search.value.focus()), which uses a template ref from the Lifecycle Hooks lesson (const search = useTemplateRef("search")and<input ref="search">). The difference is that a directive packages that code, so any element needs just one attribute.
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 } |
- What's inside the quotes is JavaScript, just like
:price.v-color="blue"reads the variableblue. For text, put quotes inside the quotes:v-color="'blue'". argandmodifierslet one directive work in several ways. For example,v-price:shortcould write$30instead of$30.00.
Registering a directive
<script setup>: a variable with thevprefix, likevFocus, is enough. That directive works in that component only.- A component without
<script setup>: through thedirectivesoption,directives: { focus: vFocus }. The name is written withoutv-, then used asv-focus. - Globally:
app.directive("focus", vFocus)inmain.js, beforeapp.mount("#app"). After that,v-focusworks in every component.
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" />
- In the first exercise, you use this form for
v-focus:vFocusgetsmounted(el) { el.focus() }, the childSearchBoxregisters it throughdirectives: { focus: vFocus }, and its template has<input id="auto-focus" v-focus />. The checker makes sure the browser's focus really is on#auto-focus. - In the second exercise, you make
v-pricein a childCashier: themountedandupdatedhooks setel.textContentto"$" + binding.value.toFixed(2). So#totalreads$15.00, then$30.00after the#addbutton is clicked.
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
const focus = { ... }in<script setup>isn't connected tov-focus, because its name doesn't start with v. In development mode, the console writes[Vue warn]: Failed to resolve directive: focus. Writeconst vFocus.- A directive with only
mountedlets its text go stale: the text keeps the old number after the data changes. Addupdated, or write the directive as a function. - Focus can't be given in setup. When setup runs, the element doesn't exist yet, and what the template ref holds, for example
inputRef.value, is stillnull. So JavaScript stops with the errorCannot read properties of null (reading 'focus'). Callfocus()inonMountedor in themountedhook. - In the second exercise, don't forget
updated. Withmountedalone,#totalstays$15.00after#addis clicked. Writeupdatedwith the same body, or writevPriceas a function.
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.