separating v-if and v-for Vue.js 3

Viewed 1137

I have read that we shouldn't put v-if and v-for together in vuejs. I've also got an error in the IDE. How am I suppose to separate the v-if and v-for in my code so that it follows the style guide?

<div
        v-for="(value, key, index) in items"
        v-if="value.level === undefined || value.level < level"
        :key="key"
      >

level is a computed value too

computed: {
    level() {
      return (
         user.access>3
      );
    }
  },
3 Answers

You can use invisible wrapper (<template>) element with v-if. Benefit of using this is template won't render until condition met. You can read more about template here

Example:

<div v-for="(value, key, index) in items" :key="key">
  <template v-if="value.level === undefined || value.level < level"> // It won't render until v-if = true
   ....

put the v-if directive in a virtual element template :


<div   v-for="(value, key, index) in items" :key="key">
   <template v-if="value.level === undefined || value.level < level">
    ....

If you don't want a bunch of empty divs on the dom, filter it.

computed: {
   filtered_items: function() {
     return this.items.filter(v => typeof v.level === 'undefined' || v.level < this.level)
   }
},

Then use filtered_items instead of items in the v-for

Can also do inline:

v-for="item in items.filter(v => typeof v.level === 'undefined' || v.level < level)"

Related