# Template Syntax — Vue.js

Source: https://www.skillbyai.com/en/vue/f-template

> Interpolation, directives, conditionals and lists.

## Directives connect templates to state

Text interpolation `{{ expr }}` renders a JavaScript expression as text (HTML is escaped). **Directives** are special attributes starting with `v-`: `v-bind:href` (shorthand `:href`) binds an attribute to an expression, `v-on:click` (shorthand `@click`) attaches an event listener, with modifiers such as `.prevent` and `.stop`. `v-if` / `v-else-if` / `v-else` add or remove elements, while `v-show` keeps the element and toggles CSS `display`, which is cheaper for frequent toggling. `v-for="item in items"` renders a list and should always have a unique `:key` so Vue can track each item when the list changes. Avoid `v-if` and `v-for` on the same element; wrap with a `<template>` instead.

## The common directives together

A small todo list.

```vue
<script setup>
import { ref } from 'vue'

const todos = ref([
  { id: 1, text: 'Learn templates', done: true },
  { id: 2, text: 'Learn reactivity', done: false },
])
const showDone = ref(true)
const docsUrl = 'https://vuejs.org'
</script>

<template>
  <a :href="docsUrl" target="_blank">Docs</a>
  <button @click="showDone = !showDone">Toggle done</button>

  <ul>
    <template v-for="todo in todos" :key="todo.id">
      <li v-if="showDone || !todo.done">{{ todo.text }}</li>
    </template>
  </ul>
  <p v-show="todos.length === 0">Nothing to do</p>
</template>
```

## Do not use the index as a key for changing lists

If items can be reordered, inserted or removed, an index key makes Vue reuse the wrong DOM nodes and component state. Use a stable id from your data.

**Quiz:** What is the difference between v-if and v-show?

- [ ] v-if only works on components
- [ ] They are identical aliases
- [ ] v-show removes the element from the DOM
- [x] v-if adds or removes the element; v-show only toggles its CSS display

*Answer:* v-if adds or removes the element; v-show only toggles its CSS display. Choose v-show for frequent toggles, v-if for rarely shown content.
