1. Overview
In this article, we will learn to use v-if and v-for together in Vue js 3. To learn more about Vue, refer to these articles.
2. Precedence
There are scenarios where you want to use both these two most commonly used directives v-if
and v-for
in the same element.
In 2.x, when using v-if
and v-for
on the same element, v-for
would take precedence. In 3.x, v-if
will always have higher precedence than v-for
.
The v-if condition can conditionally render an element or a template fragment based on the truthy-ness of the expression value.
3. Vue v-for directive
We can use the v-for
directive to render a list of items based on an array. The v-for
directive requires a special syntax as item in items
, where items
is the source data array and item
is an alias for the array element being iterated on:
<script> export default { data() { return { todos: { name: 'Send email', isComplete: true } } } } </script> <template> <li v-for="todo in todos"> {{ todo.name }} </li> </template>
4. v-for
with v-if
While using v-for
with v-if
, the v-if
condition will not have access to variables from the v-for
scope:
<!-- This will throw an error because property "todo" is not defined on instance. --> <li v-for="todo in todos" v-if="!todo.isComplete"> {{ todo.name }} </li>
However, if you still want to access it within v-if
, you can move v-for
to a wrapping <template>
tag (which is also more explicit):
template
<template v-for="todo in todos"> <li v-if="!todo.isComplete"> {{ todo.name }} </li> </template>
4. Conclusion
To sum up, we have learned to use the v-if, v-for directives together.