Vue js Directives


Introduction

In Vue.js, directives are extended HTML-like instructions prefixed with v-. These add reactive and behavioral capabilities to normal HTML elements.

These custom attributes interact closely with the underlying Vue setup to reflect real-time changes on the webpage.

Instead of writing long JavaScript blocks, Vue allows developers to handle logic elegantly through these built-in shorthand tools.


Assorted Vue.js Directives

Below are unique descriptions for several built-in Vue directives:

Directive Purpose
v-bind Attaches HTML attribute values dynamically based on internal Vue data.
v-if Shows elements conditionally. Accompanied optionally by v-else-if and v-else to handle logic trees.
v-show Controls visibility of a tag without adding/removing it from the DOM.
v-for Loops over iterable data like arrays or objects and builds repeated content.
v-on Binds browser events (click, hover, submit) to Vue-defined actions or functions.
v-model Enables two-way communication between form controls (like input, select) and application state.

Sample: Using v-bind

The following is a basic demonstration of how v-bind dynamically links class names:

<!DOCTYPE html>
<html>
<head>
  <style>
    .highlight {
      background-color: gold;
    }
  </style>
</head>
<body>
  <div id="sampleApp">
    <section v-bind:class="activeStyle">Hello!</section>
  </div>

  <script src="https://unpkg.com/vue@3"></script>
  <script>
    const sampleApp = Vue.createApp({
      data() {
        return {
          activeStyle: 'highlight'
        }
      }
    })
    sampleApp.mount('#sampleApp')
  </script>
</body>
</html>

            

This snippet illustrates how the

picks its CSS class through Vue's reactive data instead of static HTML.


Learn by Doing

Hands-on exploration helps solidify concepts. Try modifying directive values, conditions, or events to get a feel for Vue’s flexible system. As you explore more, you'll notice how powerful and streamlined Vue becomes for interactive UI creation.


Prefer Learning by Watching?

Watch these YouTube tutorials to understand VUE JS Tutorial visually:

What You'll Learn:
  • 📌 Let's Learn VueJS #3 - Vue Directives
  • 📌 Vue JS 2 Tutorial #34 - Custom Directives
Previous Next