0
0
Vueframework~5 mins

v-for with v-if precedence in Vue

Choose your learning style9 modes available
Introduction

We use v-for to repeat elements for each item in a list. v-if decides if an element should show or not. Knowing which runs first helps avoid mistakes.

Showing a list of tasks but only those that are not done.
Displaying user comments but skipping empty ones.
Rendering menu items but hiding some based on user role.
Looping through products but only showing those in stock.
Syntax
Vue
<element v-for="item in items" v-if="condition">...</element>

v-for runs before v-if. It creates the list first, then v-if decides which items to show.

For better performance, avoid putting v-if on the same element as v-for. Instead, filter the list in JavaScript or use a computed property.

Examples
This loops over all tasks, then shows only those not done.
Vue
<li v-for="task in tasks" v-if="!task.done">{{ task.name }}</li>
Using <template> to separate v-for and v-if for clarity.
Vue
<template v-for="task in tasks" v-if="!task.done">
  <li>{{ task.name }}</li>
</template>
Better way: filter tasks in a computed property, then loop only filtered tasks.
Vue
<li v-for="task in filteredTasks">{{ task.name }}</li>
Sample Program

This component loops over items. It shows only items where show is true. So Banana is skipped.

Vue
<template>
  <ul>
    <li v-for="item in items" v-if="item.show" :key="item.id">
      {{ item.text }}
    </li>
  </ul>
</template>

<script setup>
import { ref } from 'vue'

const items = ref([
  { id: 1, text: 'Apple', show: true },
  { id: 2, text: 'Banana', show: false },
  { id: 3, text: 'Cherry', show: true }
])
</script>
OutputSuccess
Important Notes

Remember, v-for runs first, then v-if. So the list is made, then filtered.

Using v-if inside v-for can hurt performance if the list is big.

Better to filter data before looping when possible.

Summary

v-for creates the list first.

v-if decides which items to show after.

For better speed, filter data before using v-for.