Vue.js / Vue Directives and Templates

Directive Usage

In this tutorial, we'll explore how to properly use directives in Vue.js. We'll cover both built-in and custom directives, showcasing their ability to dynamically manipulate the D…

Tutorial 1 of 4 4 resources in this section

Section overview

4 resources

Explains the use of Vue directives and templates to enhance UI interactivity.

Vue.js Directives Tutorial

1. Introduction

In this tutorial, we will be discussing the use of directives in Vue.js. Directives are a unique and powerful feature in Vue.js that allows us to directly manipulate the DOM. They start with the v- prefix and are embedded right in the HTML markup.

By the end of this tutorial, you will have a strong understanding of:

  • How to use built-in directives
  • How to create and use custom directives

Prerequisites for this tutorial include a basic understanding of HTML, CSS, and JavaScript, as well as a basic understanding of Vue.js.

2. Step-by-Step Guide

Understanding Directives

Directives are special attributes with the v- prefix. They are expected to be used on a single element in the template. When the Vue instance is created, Vue compiles the templates and transforms the directives into pure JavaScript code.

Built-in Directives

Vue.js comes with several built-in directives, such as v-model, v-if, v-for, and v-show.

For example, v-model is a two-way binding directive. It’s mostly used with form elements such as input, select and textarea.

<input v-model="message" placeholder="Enter something..."/>
<p>Message is: {{ message }}</p>

v-if is a conditional directive. It will only render the element if the directive's expression returns a truthy value.

<p v-if="seen">Now you see me</p>

Custom Directives

Apart from the default set of directives shipped with Vue, it also allows us to register our own custom directives.

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

Here, we are creating a custom directive called focus. This directive, when applied to an element, will automatically focus that element when it is inserted into the DOM.

3. Code Examples

Using v-for Directive to Render a List

<ul id="example-1">
  <li v-for="item in items">
    {{ item.message }}
  </li>
</ul>
var example1 = new Vue({
  el: '#example-1',
  data: {
    items: [
      { message: 'Foo' },
      { message: 'Bar' }
    ]
  }
})

In this example, we use the v-for directive to render a list of items based on an array. The v-for directive requires a special syntax in the form of item in items, where items is the source data array and item is an alias for the array element being iterated on.

Using Custom Directive

<input v-focus>
Vue.directive('focus', {
  inserted: function (el) {
    el.focus()
  }
})

In this example, we use the custom v-focus directive to automatically focus the input element when it is inserted into the DOM.

4. Summary

In this tutorial, we've learned about the power of directives in Vue.js. We've covered both built-in and custom directives, showcasing their ability to dynamically manipulate the DOM.

You can continue learning about Vue.js by exploring other features such as components, mixins, and transitions. The Vue.js guide and API documentation are good places to start.

5. Practice Exercises

  1. Create a Vue instance where you use the v-if directive to conditionally render a paragraph element.

  2. Use the v-for directive to render a list of items, where each item is an object with properties name and age.

  3. Create a custom directive v-color that changes the color of a text element to any color you specify.

Remember, the best way to learn is by doing. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random Number Generator

Generate random numbers between specified ranges.

Use tool

Backlink Checker

Analyze and validate backlinks.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help