...

/

Template Syntax: Directives

Template Syntax: Directives

Learn about the v-for, v-if, and v-bind directives.

Directives

To build any sort of interesting UI, we need to do more than just display simple values. Vue’s template syntax includes directives for looping and conditional display logic, as well as binding HTML attributes to reactive data properties. Directives are attributes we add to DOM elements and components very similar to AngularJS’s ng-* directivesAngularJS's ng-* directives stands for "Angular JavaScript Directives," which are HTML attributes used to extend and enhance the behavior of HTML elements within AngularJS applications..

The v-for directive

Thinking back to our example instance dataIn Vue.js, instance data refers to the data properties defined within a Vue component. These properties hold the state or information that the component uses to render and manage its behavior., we’ve probably already thought about how we go about looping over collections of data such as arrays.

The v-for directive allows us to tell Vue that we want a section of our template to be rendered for every item in a collection (which can be an array or an object).

Syntax

Press + to interact
<div v-for="item in items" :key="item.id">
<!-- Content to be repeated for each item -->
{{ item }}
</div>
  • v-for: This is the directive used to create a loop in the Vue template.

  • item: It represents the individual item in the items array that will be used in each iteration of the loop. We can choose any variable name to represent each item (e.g., employee, product, etc.).

  • items: It’s the array that we want to loop through. The v-for directive will iterate over each element of the items array.

  • :key: This is a special attribute that must be used when using v-for to help Vue.js keep track of the elements in the loop and efficiently update the DOM. It requires a unique identifier for each item, usually using a property like id from the array items.

Code example

Here, the tr element with the v-for directive and all its child ...