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
The v-for
directive
Thinking back to our example
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
<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 theitems
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. Thev-for
directive will iterate over each element of theitems
array.:key
: This is a special attribute that must be used when usingv-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 likeid
from the array items.
Code example
Here, the tr
element with the v-for
directive and all its child ...