Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Directives

A directive is a special template attribute that starts with v-. It tells Vue what to do with an element: show it on a condition, repeat it for every array item, link it to an input field. You have already met one directive — v-bind.

Syntax

v-on:click.prevent="save"
 │    │      │        │
 │    │      │        └─ value: a JavaScript expression
 │    │      └─ modifier (optional)
 │    └─ argument (optional)
 └─ directive name

A directive's value is an expression, just like inside double curly braces. The argument says what the directive applies to: for v-bind it is the attribute name, for v-on the event name. A modifier changes the behaviour, for example .prevent cancels the browser's default action.

Main directives

DirectiveShort formWhat it does
v-bind:href:hrefPuts a value into an attribute
v-on:click@clickRuns code on an event
v-if, v-else—Adds or removes an element on a condition
v-show—Hides an element with CSS
v-for—Repeats an element for each value
v-model—Links an input field to a variable
v-html—Inserts ready-made HTML

Each of them has its own lesson. Here is a short introduction.

Example

<!-- src/App.vue -->
<script setup>
const tasks = ['Buy bread', 'Call Anna']
const showHint = true
 
function sayHi() {
  alert('Hello!')
}
</script>
 
<template>
  <p v-if="showHint">Press the button to say hello.</p>
  <button @click="sayHi">Hello</button>
  <ul>
    <li v-for="task in tasks" :key="task">{{ task }}</li>
  </ul>
</template>

The page shows a hint, a button and a list of two tasks. Clicking the button opens a "Hello!" dialog. v-if decides whether to render the paragraph, @click attaches a handler, v-for repeats li for every string of the array.

Dynamic argument

The argument can also come from a variable — it is written in square brackets:

<script setup>
const attr = 'title'
</script>
 
<template>
  <h1 :[attr]="'Hint'">My tasks</h1>
</template>

The heading gets a title attribute. You rarely need this, but it helps to recognise it in other people's code.

Common mistake

A directive's value is code, not text. v-if="false" really hides the element, and both @click="sayHi()" and @click="sayHi" work. But :href="https://example.com" is a compile error: Vue tries to run the address as JavaScript. Wrap a string inside a directive in single quotes: :href="'https://example.com'", and if the value never changes, write a plain attribute without the colon.

Thanks for reading!

Donate to the site — we work hard for you.