Search code examples
javascriptvue.jsfiltervuetify.jsv-for

How to deactivate or define for all cases v-if in v-for in vue?


I have a v-for in which I use v-if. If variable choice has value "a", display only elements with label.type is "a". If "b" display elements with label.type is "b". How can I make v-if display everything, if, for example choice has value "c"? Is it possible to deactivate v-if or something? Is there an easier way to do this?

<v-card v-for="label in labels" v-bind:item="label" v-bind:key="label._id">
  <div v-if="label.type === filter> {{ label.key }}
  </div>
</v-card>
  computed: {
    filter() {
      let filter= this.choice === "a"? "a" : "b";
      return filter;
    }
  }

Solution

  • I'd probably just evaluate your if in a method, then you can add all the additional logic you need to.

    methods: {
      shouldDisplayLabel(type) {
        // if choice is c, display everything
        if(this.choice === 'c') return true;
    
        // check if choice matches the label type
        return this.choice === type;
      }
    }
    

    Then your template could look like this:

    <v-card v-for="label in labels" v-bind:item="label" v-bind:key="label._id">
      <div v-if="shouldDisplayLabel(label.type)"> {{ label.key }}
      </div>
    </v-card>