Rendering Lists with v-for
This comes in extremely handy, especially when you are building a component that has a list of similar data that needs to be displayed. The v-for is a Vue directive that can be used to loop through an array. As you’ve done before, Copy down the code from the image below.
Let us see what we’ve written up here.
- The data section has a variable called cars. This variable is a JSON array of people and their cars.
- In the template section, we have looped a div with a v-for.
- The item property contains the current element whereas the index is the count of the current iteration.
- A key-value has been set giving each div a unique key.
- Inside the div, we have a paragraph printing out data from the JSON object.
It is also very important to note that this will not generate list of <p> elements, but a list of <div> elements since <p> is nested.
If all goes well for you, the following output should be achieved. There might be changes due to CSS but the content should be the same.
Here is something that I want you to know. In Normal HTML, when you want to hide something, you set its CSS attribute display:none;. However, when you are using Vue HTML needs to be rendered. This means that it would be a total waste to render everything then eventually hide things that are not needed with CSS. The solution is to not render them in the first place.
This isn’t rocket science at all. We will just be using if and else statements. These if and else statements are called v-if and v-else directives.
Quickly replicate the following code on your systems.
- We have an input box that stores its value in a variable called num.
- We have a computed property called input_even. This value is set to true or false depending upon whether the num variable is an even number.
- In the template section, we are using a simple v-if to check for Boolean. If the condition is true, the first element is rendered, else the latter one.
We can use as many v-if and v-else ladders also, nesting is truly supported. The templates for conditions that are not true are never rendered so they never reach the browser’s dom.
If all goes well, you can expect the following output when you enter an even number.
Vue has directives that make templating easier. Rendering a list of items becomes a piece of cake with the v-for directive. The v-if and v-else directives help save time by rendering only the components that are needed. I am sure you have grasped the concepts of lists and conditions in Vue templates. If you are still confused about something from the article, let me know in the comment section.