Home > Net >  How can we use v-for and v-if in the same element?
How can we use v-for and v-if in the same element?

Time:07-10

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?

CodePudding user response:

The Vue.js Style Guide recommends against this:

Never use v-if on the same element as v-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 the v-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, 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.

CodePudding user response:

Prayush.

I believe you just need to specify them both on the component. Nothing special is required.

  • Related