What is Template in Vue: Explanation and Example
template is a special HTML-like block that defines the structure and layout of the user interface for a component. It tells Vue what to display on the screen by combining HTML with Vue's special syntax for dynamic content and bindings.How It Works
Think of a Vue template as a blueprint for a house. It shows the shape and arrangement of rooms (elements) but doesn’t build the house itself. Vue reads this blueprint and creates the actual house (the rendered web page) based on it.
The template uses normal HTML tags mixed with special Vue features like {{ }} for showing dynamic data and directives like v-if or v-for to control what appears and how many times. Vue then turns this template into real HTML that the browser can display.
This separation lets you focus on designing the UI structure clearly, while Vue handles updating the page when data changes, making your app interactive and fast.
Example
This example shows a simple Vue component with a template that displays a greeting message and a list of items.
<template>
<div>
<h1>Hello, {{ name }}!</h1>
<ul>
<li v-for="item in items" :key="item">{{ item }}</li>
</ul>
</div>
</template>
<script setup>
import { ref } from 'vue'
const name = ref('Friend')
const items = ref(['Apple', 'Banana', 'Cherry'])
</script>When to Use
Use a template in Vue whenever you want to define what your component should show on the screen. It is the main way to build the visual part of your app.
Templates are perfect for creating reusable UI pieces like buttons, forms, lists, or entire pages. They help keep your code organized by separating the look (template) from the logic (script) and styles (CSS).
For example, if you want to show a list of products that updates when new items arrive, you write the HTML structure in the template and let Vue update it automatically when the data changes.
Key Points
- A
templatedefines the HTML structure of a Vue component. - It mixes HTML with Vue syntax to show dynamic data and control rendering.
- Vue compiles the template into real HTML that updates automatically when data changes.
- Templates keep UI code clear and separate from logic and styles.