Learn Vue.js · 2/13

Template Syntax: Rendering the UI

8 min read

In web development, you are constantly trying to take raw data (like a user's name or a list of products) and display it on a screen.

Vue.js uses an HTML-based template syntax. This means that underneath the hood, Vue compiles your templates into highly optimized JavaScript code that figures out exactly what needs to update in the browser when your data changes.

In this guide, we will break down how to render and manipulate the UI using Vue's template features.


1. Text Interpolation and The Mustache Syntax

The Problem

Traditional HTML is static. If you write <p>Hello, John</p>, it will always say "Hello, John." But modern applications are dynamic. You need the application to say "Hello" to whoever happens to be logged in. Without a framework, you would have to manually select the HTML element using JavaScript (document.getElementById) and forcefully overwrite its inner text. Doing this for hundreds of data points is unmaintainable.

The Definition and Solution

Text Interpolation is the process of evaluating a JavaScript variable or expression and injecting its result directly into the text content of an HTML element.

Vue solves the problem of static HTML using the "Mustache" syntax—double curly braces {{ }}.

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

// The data
const username = ref('Alice');
const unreadMessages = ref(5);
</script>

<template>
  <!-- The Mustache syntax in action -->
  <h1>Hello, {{ username }}!</h1>
  <p>You have {{ unreadMessages }} unread messages.</p>
</template>

Whenever the value of username or unreadMessages changes in your JavaScript, Vue will instantly and automatically update the text inside the HTML.

Industry Standards & Usage

You can place basic JavaScript expressions inside the mustaches. However, a strict industry standard is to never put complex logic inside your templates.

Templates are meant to be a declarative blueprint of your UI, not a place to process heavy calculations.

vue
<!-- ✅ GOOD: Simple ternary operations or basic math -->
<p>{{ unreadMessages > 0 ? 'You have mail' : 'No mail' }}</p>
<p>Total cost: ${{ price * quantity }}</p>

<!-- ❌ BAD: Complex logic inside the template -->
<p>{{ text.split('').reverse().join('') }}</p>

If you find yourself writing complex JavaScript inside {{ }}, move it into a computed property in your <script> tag instead.


2. Binding HTML Attributes with v-bind

The Problem

The mustache syntax {{ }} only works for injecting text inside an element's tags. It does not work inside HTML attributes.

If you try to do this: <img src="{{ dynamicImagePath }}">, Vue will throw a catastrophic error, and the browser will literally try to load an image from a URL called http://yoursite.com/{{ dynamicImagePath }}, which obviously does not exist.

The Definition and Solution

Attribute Binding is the process of linking an HTML attribute to a JavaScript variable, so that the attribute's value updates whenever the variable changes.

To solve this, Vue provides a special directive called v-bind.

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

const imagePath = ref('/images/profile.jpg');
const isButtonDisabled = ref(true);
</script>

<template>
  <!-- Using v-bind to set the src attribute -->
  <img v-bind:src="imagePath" alt="User Profile">

  <!-- Using v-bind for boolean attributes -->
  <button v-bind:disabled="isButtonDisabled">Submit</button>
</template>

Industry Standards & Usage (The Shorthand)

In the industry, you will almost never see a developer type out v-bind:. It is so frequently used that Vue provides a shorthand: the colon :.

vue
<!-- ✅ STANDARD: Use the colon shorthand -->
<img :src="imagePath" alt="User Profile">
<button :disabled="isButtonDisabled">Submit</button>

<!-- Dynamic Classes (Very Common) -->
<!-- If isError is true, the class 'error-text' is applied -->
<div :class="{ 'error-text': isError }">
  Password is too short!
</div>

Under the hood: When a boolean attribute (like disabled or checked) is bound, Vue manages it smartly. If isButtonDisabled is truthy, Vue adds the disabled attribute. If it's falsy, Vue physically removes the disabled attribute from the HTML element altogether.


3. Conditional Rendering: v-if, v-else-if, and v-show

The Problem

You don't always want users to see everything on the screen. If a user is logged out, they should see a "Login" button. If they are logged in, they should see a "Logout" button. Sending both to the browser and hoping the user doesn't click the wrong one is a recipe for disaster.

The Definition and Solution

Conditional Rendering is the process of instructing the framework to display or hide an element based on a true or false condition.

Vue provides two main ways to do this: v-if (along with v-else-if and v-else) and v-show.

1. The v-if Directive

v-if conditionally renders an element by adding or removing it entirely from the DOM (Document Object Model).

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

const userRole = ref('admin'); // Could be 'admin', 'editor', or 'guest'
</script>

<template>
  <div v-if="userRole === 'admin'">
    <h2>Admin Dashboard</h2>
    <button>Delete Database</button> <!-- Only admins have this in the DOM -->
  </div>
  
  <div v-else-if="userRole === 'editor'">
    <h2>Editor Panel</h2>
    <button>Edit Post</button>
  </div>
  
  <div v-else>
    <h2>Welcome Guest</h2>
    <button>Please Login</button>
  </div>
</template>

2. The v-show Directive

v-show also conditionally displays an element, but it does so by toggling the CSS display property. The element is always rendered in the DOM, it just might be hidden with display: none;.

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

const isMenuOpen = ref(false);
</script>

<template>
  <button @click="isMenuOpen = !isMenuOpen">Toggle Menu</button>
  
  <!-- The menu is always in the HTML structure, just visually hidden -->
  <ul v-show="isMenuOpen">
    <li>Home</li>
    <li>About</li>
  </ul>
</template>

Industry Standards & Usage: v-if vs. v-show

Imagine an office building with restricted rooms.
Using v-if is like building a room from scratch when someone needs it, and demolishing it with dynamite the moment they leave. It costs a lot of energy to build and destroy.
Using v-show is like leaving the room intact but putting a lock on the door. It takes almost zero energy to unlock or lock the door.

The Rule:

  • Use v-show if you need to toggle something very frequently (like a dropdown menu or modal). It has a higher initial load cost but very low toggle cost.
  • Use v-if if the condition is unlikely to change at runtime (like user permissions or a one-time loading screen). It has a lower initial load cost but a higher toggle cost.

4. List Rendering with v-for and the Importance of Keys

The Problem

Imagine you query your database and receive an array of 500 products. If you try to write an HTML <li> tag manually for each product, you will develop severe carpal tunnel syndrome, and your code will instantly break the moment product 501 is added. We need a way to loop through data.

The Definition and Solution

List Rendering is the process of generating a list of HTML elements based on an array or object.

Vue solves this using the v-for directive. The syntax strictly requires the format item in items, where items is the array of data and item is an alias for the array element being iterated on.

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

const shoppingList = ref([
  { id: 101, name: 'Oat Milk', price: 4.99 },
  { id: 102, name: 'Espresso Beans', price: 15.00 },
  { id: 103, name: 'Vanilla Syrup', price: 8.50 }
]);
</script>

<template>
  <ul>
    <!-- Loop through the array -->
    <li v-for="item in shoppingList" :key="item.id">
      {{ item.name }} - ${{ item.price }}
    </li>
  </ul>
</template>

The Importance of Keys (:key)

Notice the :key="item.id" in the code above? This is not optional in professional applications.

Vue's rendering engine patches the DOM efficiently. If you delete an item from the middle of a list, Vue tries to be smart. Instead of moving the HTML elements around, it just changes the text inside them to match the new array order.

If you don't use a key, Vue gets confused. Imagine a teacher handing back graded test papers to a line of students. If the students suddenly swap places and the teacher isn't checking their ID tags (keys), a student who failed might receive an A+ paper.

By binding a unique key (usually a database ID), you give Vue a trackable identifier.

Industry Standards:

  • Always provide a :key when using v-for.
  • Never use the array index (e.g., 0, 1, 2) as a key if the list can be reordered, filtered, or deleted. If an item at index 1 is deleted, the item at index 2 becomes the new index 1. The key has changed, which completely defeats the purpose of tracking elements! Use unique IDs from your data.
  • Never use v-if on the same element as v-for. v-if has a higher priority than v-for in modern Vue, so the v-if condition won't have access to the loop variables. Instead, wrap the v-for inside a <template> tag or compute a filtered list in JavaScript first.

Further Reading & References

To deepen your understanding and see edge-case scenarios, consult the official Vue documentation:

Challenge

Challenge: Create a Dynamic Product Listing Component

You are tasked with building a product display component in Vue.js. You will be given a products array in the <script setup> block. Your goal is to render this data dynamically in the template using the core Vue directives.

Requirements:

  1. List Rendering: Use the v-for directive to iterate over the products array. For each product, create a div with the class product-card.

    • Crucially, you must bind a unique :key to each product-card using the product's id.
  2. Text Interpolation: Inside each product-card, display the product's name in an h3 tag and its price in a p tag. The price should be prefixed with a dollar sign, like so: Price: ${{ product.price }}.

  3. Attribute Binding:

    • Add an img tag and dynamically bind its src attribute to the product's imageUrl.
    • Add an "Add to Cart" <button>. This button must be dynamically disabled (using :disabled) if the inStock property for the product is false.
  4. Conditional Class Binding:

    • On the p tag that displays the price, conditionally bind a class named on-sale only if the product's price is less than 50.
  5. Conditional Rendering:

    • Use v-if to render a span with the class featured-badge and the text "Featured!" but only if the product's isFeatured property is true.
    • Use v-if and v-else to display the stock status. If inStock is true, render a p tag with the text "In Stock". If it's false, render a p tag with the text "Out of Stock".

Expected result

Your completed code should render three product cards within the #product-list div.

For the "Ergonomic Keyboard":

  • It must have a div with :key="'p1'".
  • It must display the name Ergonomic Keyboard and the text Price: 75.
  • The price element should not have the on-sale class.
  • It must display a span with the text "Featured!".
  • The "Add to Cart" button should be enabled (no disabled attribute).
  • It must display the text "In Stock".

For the "Wireless Mouse":

  • It must have a div with :key="'p2'".
  • It must display the name Wireless Mouse and the text Price: 45.
  • The price element must have the on-sale class.
  • The "Featured!" badge should not be present in the DOM.
  • The "Add to Cart" button must be disabled.
  • It must display the text "Out of Stock".

For the "4K Webcam":

  • It must have a div with :key="'p3'".
  • It must display the name 4K Webcam and the text Price: 120.
  • The price element should not have the on-sale class.
  • The "Featured!" badge should not be present.
  • The "Add to Cart" button should be enabled.
  • It must display the text "In Stock".
html

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.