Iterating Over Lists with v-for
Hello, students! Welcome to Lesson 5 of Vue.js Directives. Today, we will learn about the v-for
directive and how to use it to iterate over lists.
What is the v-for Directive?
The v-for
directive allows iterating over a list and rendering an element for each item in the list.
How to Use the v-for Directive?
The basic syntax of the v-for
directive is as follows:
<element v-for="item in list">
Where:
element
is the element you want to render for each item in the list.item
is a variable representing the current element in the list.list
is the list you want to iterate over.
Example
Let’s see an example of how to use the v-for
directive to iterate over a list of tasks:
<ul> <li v-for="task in tasks"> {{ task }} </li> </ul>
In the example above, the v-for
directive will iterate over the tasks
list and render an li
element for each item in the list. The task
variable will represent the current element in the list.
Other Examples
Let’s see some other examples of how to use the v-for
directive:
- Iterating over a list of names:
<ul> <li v-for="name in names"> {{ name }} </li> </ul>
- Iterating over a list of numbers:
<ul> <li v-for="number in numbers"> {{ number }} </li> </ul>
- Iterating over a list of objects:
<ul> <li v-for="object in objects"> {{ object.name }} </li> </ul>
JavaScript Expressions in the v-for Directive
You can use JavaScript expressions in the v-for
directive to determine how the list items are rendered.
For example, let’s see an example of how to use the v-for
directive to iterate over a list of tasks and display the creation date of each task:
<ul> <li v-for="task in tasks"> {{ task.creationDate }} </li> </ul>
In the example above, the v-for
directive will iterate over the tasks
list and render the value of the creationDate
property for each item in the list.
Conclusion
The v-for
directive is a powerful tool that can be used to iterate over lists. It is one of the most important directives in Vue.js and is essential to learn when using Vue.js.
In the next module, we will learn about event handling in Vue.js. We will learn how to listen to events and respond to them.
Challenge
Here’s a challenge for you:
- Create a Vue.js application that displays a list of tasks. Each task should include the task title, task creation date, and task status.
Good luck!
Tip
You can use the v-for
directive to create a component that can be used to render a list of any type of data.