Template Syntax and Directives

Learn template syntax, common and custom directives, filters, and dynamic class and style bindings through beginner-friendly examples.

🎯 Introduction

By the end of this article, you will be able to build dynamic pages with template syntax and bind data to the view effectively. Common directives, custom directives, filters, and dynamic style bindings help you write concise, flexible, maintainable frontend code for a wide range of projects.


📝 Template Syntax Basics

Template syntax connects a framework's view with its data. Special syntax lets HTML respond to data changes and render page content dynamically. Understanding template syntax is an essential step toward understanding how frontend frameworks work.

For example, suppose you have a variable called name. Writing its name directly in HTML will not make the page respond to changes in that variable. Binding it with template syntax keeps the displayed name in sync with the data.

example.vue
<template>
    <div>Hello, {{ name }}!</div>
</template>

<script>
export default {
    data() {
        return {
            name: 'xiaoming',
        };
    },
};
</script>

Here, {{ name }} renders the variable's value on the page.

Double curly braces {{}} bind text, providing a convenient way to display variable values.

🔧 Common Directives

Directives are a core part of template syntax and provide powerful ways to work with the DOM. The following sections introduce several common, fundamental directives.

v-bind: Attribute Binding

v-bind dynamically binds element attributes such as class, id, and src. It also supports a shorthand syntax for attribute bindings.

example.vue
<template>
    <div>
        <img v-bind:src="imageUrl" alt="Dynamic image" />

        <!-- Shorthand syntax -->
        <img :src="imageUrl" alt="Dynamic image" />
    </div>
</template>

<script>
export default {
    data() {
        return {
            imageUrl: 'xiaoming.png',
        };
    },
};
</script>

Here, imageUrl is the bound variable. The image source changes when its value changes.

v-bind keeps element attributes in sync with data, reducing manual DOM manipulation and simplifying development.

v-model: Two-Way Binding for Form Inputs

v-model creates a two-way binding between form inputs and data. User input updates the data, and data changes update the view.

example.vue
<template>
    <div>
        <p>Username entered: {{ username }}</p>
        <input type="text" v-model="username" placeholder="Enter a username" />
    </div>
</template>

<script>
export default {
    data() {
        return {
            username: '',
        };
    },
};
</script>

The input is bound to username: typing updates the variable, and changing the variable updates the input.

v-model is commonly used with form elements such as input, textarea, and select to simplify handling user interactions.

v-if: Conditional Rendering

v-if controls whether an element is rendered. The truthiness of its expression determines whether the element exists in the DOM.

example.vue
<template>
    <div>
        <p v-if="isLoggedIn">Welcome back!</p>
        <p v-else>Please log in first</p>
    </div>
</template>

<script>
export default {
    data() {
        return {
            isLoggedIn: false,
        };
    },
};
</script>

When isLoggedIn is true, the welcome message appears; otherwise, the login prompt appears.

v-if actually destroys or creates elements, so frequent toggling can affect performance. For simply showing and hiding content, consider v-show.

v-for: List Rendering

v-for iterates over an array or object to generate multiple elements.

example.vue
<template>
    <ul>
        <li v-for="(item, index) in items" :key="index">{{ item }}</li>
    </ul>
</template>

<script>
export default {
    data() {
        return {
            items: ['Apple', 'Banana', 'Orange'],
        };
    },
};
</script>

This code dynamically generates a list of fruit.

Using :key helps Vue track rendered items and avoid rendering errors. It is recommended to always provide a key.

🛠 Custom Directives

In addition to built-in directives, you can define your own to implement specific DOM behavior. Custom directives are useful for encapsulating common behaviors such as autofocus and dragging.

main.js
import Vue from 'vue';

Vue.directive('focus', {
    inserted(el) {
        el.focus();
    },
});

Use it in a template:

example.vue
<template>
    <input v-focus placeholder="Automatically focused on page load" />
</template>

This directive automatically focuses the input when the page loads.

Common Vue 2 custom directive hooks include inserted, update, and componentUpdated. inserted runs when the element is inserted into its parent node. update runs when the containing component's VNode updates. componentUpdated runs after the VNodes of the containing component and its children have all updated.

🔄 Filters

Filters format output, such as dates or numbers, using a concise, readable syntax.

main.js
Vue.filter('capitalize', function (value) {
    if (!value) return '';
    return value.charAt(0).toUpperCase() + value.slice(1);
});

Use it in a template:

example.vue
<template>
    <p>{{ message | capitalize }}</p>
</template>

<script>
export default {
    data() {
        return {
            message: 'helloworld',
        };
    },
};
</script>

This capitalizes the first letter of message.

Vue 2 supports filters, but Vue 3 has removed them. When migrating to Vue 3, use computed properties or methods for similar tasks.

🎨 Dynamic Class and Style Bindings

Style bindings are an important part of interactive frontend pages. Dynamic bindings let styles respond to data changes and improve the user experience.

Dynamic Class Bindings

Class bindings accept strings, objects, or arrays, providing flexible control over styles.

example.vue
<template>
    <div :class="{ active: isActive, 'text-danger': hasError }">Dynamic classes</div>
</template>

<script>
export default {
    data() {
        return {
            isActive: true,
            hasError: true,
        };
    },
};
</script>

When isActive is true, the element receives the active class. When hasError is true, it receives the text-danger class.


Dynamic Style Bindings

v-bind:style accepts objects or arrays to set inline styles dynamically.

example.vue
<template>
    <div :style="{ color: activeColor, fontSize: fontSize + 'px' }">Dynamic styles</div>
</template>

<script>
export default {
    data() {
        return {
            activeColor: 'red',
            fontSize: 14,
        };
    },
};
</script>

The element's styles update whenever activeColor or fontSize changes.

Dynamic style bindings make pages more flexible and help provide visual feedback for interactions.

❓ Questions and Answers

Q1: What is the difference between v-bind and v-model?

v-bind binds element attributes in one direction, from data to the view. v-model provides two-way binding for form inputs: user input updates the data, and data changes update the view.

Q2: Why should you use a key with v-for?

A key helps the framework track each node, improving rendering efficiency and preventing rendering errors.

Q3: What are common custom directive hooks?

Common hooks are inserted, update, and componentUpdated. They run when the element is inserted into its parent, when the containing component's VNode updates, and after the VNodes of that component and its children have all updated, respectively.


🧪 Exercises

Exercise 1: Autofocus an Input

Create a custom directive called v-focus that automatically focuses an input when its element is mounted.

example.vue
<template>
    <div>
        <input v-model="name" v-focus placeholder="Automatically focused on page load" />
    </div>
</template>

<script>
export default {
    data() {
        return {
            name: '',
        };
    },
};
</script>
main.js
Vue.directive('focus', {
    // Implement the directive logic
});

Exercise 2: Change Color on Click

Create a custom directive called v-color-toggle that toggles an element's text color between red and blue when clicked.

example.vue
<template>
    <div>
        <p v-color-toggle style="cursor: pointer">Click to toggle the color</p>
    </div>
</template>
main.js
Vue.directive('color-toggle', {
    // Implement the directive logic
});

🎉 You have covered template syntax, common directives, custom directives, filters, and dynamic style bindings. These skills help you write frontend code more efficiently and effectively. Keep practicing and applying them!