SoFunction
Updated on 2025-04-05

Tutorial on vue's attention specifications: v-if and v-for

When v-if  is used with v-for , v-for  has a higher priority than v-if , which means v-if  will be run repeatedly in each v-for loop, respectively

Therefore, it is not recommended to use v-if and v-for at the same time

Recommended ways to use:

<ul>
<li
v-for="user in activeUsers"
:key=""
>
{{  }}
</li>
</ul>
<ul v-if="shouldShowUsers">
<li
v-for="user in users"
:key=""
>
{{  }}
</li>
</ul>

Or: put in the calculation attribute traversal

computed: {
activeUsers: function () {
return (function (user) {
return 
})
}
}
<ul>
<li
v-for="user in activeUsers"
:key=""
>
{{  }}
</li>
</ul>

When they are at the same node, v-for has higher priority than v-if, which means v-if will be run repeatedly in each v-for loop respectively. This priority mechanism is very useful when you want to render nodes for only some items, as follows:

<li v-for="todo in todos" v-if="!">
{{ todo }}
</li>

The above code only passes on unfinished todos.

And if your purpose is to conditionally skip the execution of the loop, you can place v-if on the outer element (or <template>). like:

<ul v-if="">
<li v-for="todo in todos">
{{ todo }}
</li>
</ul>
<p v-else>No todos left!</p>

Summarize

The above is the tutorial on using v-if and v-for that I introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message. The editor will reply to you in time!