Open In App

Vue.js v-if with v-for

Last Updated : 14 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

VueJS is a popular Javascript framework used in frontend development of various web applications. Some of its features include conditionally rendering an element, looping through all the elements to display the individual element, etc. The v-if and v-for both can be used on the same element, although, firstly, the v-if will be evaluated. Generally, it is not recommended to utilize the v-if and v-for with the same element, in order to avoid the implicit precedence. In this article, we will learn how to use v-if and v-for directives together to conditionally and dynamically render the elements in the VueJS.

Approach

We will create a Vue project, and then we will use 2 different approaches to use v-if alongside v-for. In the first approach, we will wrap v-for over a v-if to limit the elements to render on UI. In the second approach, we will create a computed property to pre-filter the items that will remain in the list.

Example 1: In this example, we will use v-for as a wrapping tag over v-if. We will loop over numbers from 1 to 10 and only show the numbers on the page that are even.

HTML




<!-- App.vue -->
<template>
     <p v-for="number in numbers">
          <template v-if="number % 2 === 0">
                  {{ number }}
             </template>
     </p>
</template>
  
<script>
     export default {
          data() {
               return {
                    numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
               }
          }
     }
</script>


Output:

file

Example 2: In this example, we will create a computed property, filteredItems, to filter out the items in the list that are events.

HTML




<!-- App.vue -->
<template>
     <p v-for="number in filteredItems">
          <template v-if="number % 2 === 0">
                  {{ number }}
             </template>
     </p>
</template>
  
<script>
     export default {
          data() {
               return {
                    numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
               }
          },
          computed: {
               filteredItems() {
                    return this.numbers.filter(n => n % 2 === 0)
               }
          }
     }
</script>


Output

file

Reference: https://vuejs.org/guide/essentials/conditional.html#v-if-with-v-for



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads