Understanding Vue.JS Directives

Understanding Vue.JS Directives

Directives are special attributes used in the HTML template section of a Vue Project. They are usually prefixed with v- which serves as a visual cue for identifying them. I believe that this is vue's way of allowing you to manipulate the DOM as directives apply special reactive behavior to the rendered DOM.

The following is a list of directives that are available for use in a Vue Project:

  1. v-if

  2. v-for

  3. v-on

  4. v-model

  5. v-bind

  6. v-html

  7. v-once

  8. v-text

  9. v-pre

  10. v-cloak

I will be talking about a few of these directives and how they can be used.

v-if

This directive toggles the display or presence of the element it's placed in. It will show based on the truthiness of the value of the expression assigned to it. v-if is simply used to conditionally render a block of code.

Example 1.0

<template>
    <p v-if="seen">Yo! I can be seen.</p>
</template>

<script>
export default {
  data (){
    return{
      seen: true
    }
  }
}
</script>

In example 1.0, the p block will only show if the value of seen is set to true and will disappear if it is set to false.

v-for

This can be used to iterate or loop through a list of items using data from an array or objects.

Example 1.1

<template>
   <ul v-for="list in lists">
        <li>{{list.title}}</li>
        <li>{{list.text}}</li>
   </ul>
</template>

<script>
export default {
  data (){
    return{
      lists:[
          {title: "List 1", text: "First List"},
          {title: "List 2", text: "Second List"},
          {title: "List 3", text: "Third List"}
      ]
    }
  }
}
</script>

v-on

This directive is used to attach event listeners to elements. It allows users to interact with our application. The v-on directive usually invokes a method on the vue instance. It takes some other argument to carry out its operation.

Example 1.3

<template>
    <button v-on:click="increaseCounter">Click me</button>
     <p>Count is: {{count}}</p>
</template>

<script>
export default {
  data (){
    return{
      count:0
    }
  },
  methods:{
    increaseCounter(){
      return this.count++
    }
  }
}
</script>

v-model

This directive is used to handle user inputs. It provides two-way data binding between an app state and the form input.

Example 1.4

<template>
    <input type="text" v-model="username">Click me</button>
     <p>Your username is: {{username}}</p>
</template>

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

To learn about other Vue directives that are not discussed here, check Vue.JS documentation.