Vue Tip: Don't Use v-if With v-for
It can be tempting to use v-if
with v-for
in these common scenarios: Filtering items in a list and avoiding rendering a list if it should be hidden.
Let's take a detailed look at these two scenarios.
Filtering items in a list
You might want to write the following code to filter items in a list:
This code will throw an error because the v-if
directive will be evaluated first and the iteration variable todo
does not exist at this moment. When Vue processes directives, v-if
has a higher priority than v-for
.
You can fix the code by using a computed property that returns your filtered list:
In this example, the code doesn't loop through the entire array, only the filtered computed property, which is also cached. In case you have massive arrays, this can be a huge performance improvement.
Avoid rendering a list if it should be hidden
In some cases, you want to render a list only if a certain variable is set:
A better solution would be to move the v-if
to a container element (e.g. ul
, ol
):
StackBlitz Demo
The code of this article is interactively available at StackBlitz:
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Detect Mouse Hover
You can use Vue event handlers to detect mouse hover events.
Nuxt Tip: Lazy Load Components in Nuxt 3
Learn how you can dynamically import components in Nuxt 3 only when they’re needed.