# vue/no-use-v-if-with-v-for
disallow use v-if on the same element as v-for
- ⚙️ This rule is included in all of
"plugin:vue/vue3-essential"
,"plugin:vue/essential"
,"plugin:vue/vue3-strongly-recommended"
,"plugin:vue/strongly-recommended"
,"plugin:vue/vue3-recommended"
and"plugin:vue/recommended"
.
# 📖 Rule Details
This rule is aimed at preventing the use of v-for
directives together with v-if
directives on the same element.
There are two common cases where this can be tempting:
- To filter items in a list (e.g.
v-for="user in users" v-if="user.isActive"
). In these cases, replaceusers
with a new computed property that returns your filtered list (e.g.activeUsers
). - To avoid rendering a list if it should be hidden (e.g.
v-for="user in users" v-if="shouldShowUsers"
). In these cases, move thev-if
to a container element (e.g.ul
,ol
).
<template>
<!-- ✓ GOOD -->
<ul v-if="complete">
<TodoItem
v-for="todo in todos"
:todo="todo"
/>
</ul>
<TodoItem
v-for="todo in shownTodos"
:todo="todo"
/>
<!-- ✗ BAD -->
<TodoItem
v-if="complete"
v-for="todo in todos"
:todo="todo"
/><!-- ↑ In this case, the `v-if` should be written on the wrapper element. -->
<TodoItem
v-for="todo in todos"
v-if="todo.shown"
:todo="todo"
/><!-- ↑ In this case, the `v-for` list variable should be replace with a computed property that returns your filtered list. -->
</template>
# 🔧 Options
{
"vue/no-use-v-if-with-v-for": ["error", {
"allowUsingIterationVar": false
}]
}
allowUsingIterationVar
(boolean
) ... Enables Thev-if
directive use the reference which is to the variables which are defined by thev-for
directives. Default isfalse
.
# "allowUsingIterationVar": true
<template>
<!-- ✓ GOOD -->
<TodoItem
v-for="todo in todos"
v-if="todo.shown"
:todo="todo"
/>
<!-- ✗ BAD -->
<TodoItem
v-for="todo in todos"
v-if="shown"
:todo="todo"
/>
</template>
# 📚 Further Reading
- Style guide - Avoid v-if with v-for (opens new window)
- Guide - Conditional Rendering / v-if with v-for (opens new window)
- Guide - List Rendering / v-for with v-if (opens new window)
# 🚀 Version
This rule was introduced in eslint-plugin-vue v4.6.0