Skip to main content

What is a component template?

The component template (template) is the part of a Vue component that describes its HTML structure, that is, how the component looks on the screen.

It is a declarative way to specify what UI should be rendered, using:

  • plain HTML,
  • Vue directives (v-if, v-for, v-model),
  • expressions ({{ }}),
  • other components.

In simpler terms: a template is the component's "markup", tied to its data and logic.


Where is the template declared?

In a Single File Component (SFC), inside the <template> block:

javascript
<template> <div> <h1>{{ title }}</h1> <button @click="count++">Clicked {{ count }} times</button> </div> </template>

In this template:

  • {{ title }} and {{ count }} are bound to the state in <script>
  • @click="count++" is a reactive event
  • <div> and <button> are plain HTML

How is the template tied to the logic?

In the template we can use data, computed properties, methods, props declared in <script>.

Example:

javascript
<template> <p>Hello, {{ name }}</p> <button @click="sayHi">Say Hi</button> </template> <script setup> import { ref } from 'vue' const name = ref('Timur') function sayHi() { console.log(`Hi, ${name.value}!`) } </script>

The template "sees" every variable from <script setup>.


What can the template do?

Data interpolation

javascript
{{ message }}

Directives

javascript
<div v-if="isVisible"></div> <li v-for="item in items">{{ item }}</li> <input v-model="text">

Bindings

javascript
<img :src="imageUrl"> <button :disabled="isLoading">Save</button>

Events

javascript
<button @click="handleClick"></button>

Slots

javascript
<Modal> <template #header>Title</template> </Modal>

Using other components

javascript
<UserCard :user="user" />

Alternatives to the template

In Vue you can use a render function (JS instead of HTML), but 99% of the time <template> is used, because it is:

  • simpler,
  • more readable,
  • shorter,
  • supports syntax highlighting and autocomplete.

Example of a whole component with a template

javascript
<template> <div class="counter"> <p>Count: {{ count }}</p> <button @click="increment">+1</button> </div> </template> <script setup> import { ref } from 'vue' const count = ref(0) function increment() { count.value++ } </script> <style scoped> .counter { padding: 10px; } </style>

Summary (cheat sheet)

A component template (template) is the component's HTML markup structure, which uses:

  • data from the script,
  • directives,
  • events,
  • reactive expressions,
  • slots,
  • other components.

It determines how the component looks and how it reacts to data changes.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.