Reputation: 11
I am building a component in which I have to iterate over each action and check conditions on each action. So, how can I use v-for
and v-if
in the same element?
Upvotes: 1
Views: 2379
Reputation: 9843
The Vue.js Style Guide recommends against this:
Never use
v-if
on the same element asv-for
.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, replace users 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
).
Your best option is to use a <template>
tag for your v-for
and apply your v-if
inside that on whichever HTML tag you're using. For an instance:
<template v-for="(user, index) in users">
<div v-if="user.isActive" :key="index">
// your HTML code here
</div>
</template>
or use a computed
value as mentioned in the docs. For example, something like this:
computed: {
activeUsers() {
return this.users.filter(user => user.isActive)
}
}
Without seeing an example of your current code, I could only guess how you might adapt the above to suit your individual needs.
Upvotes: 6