Skip to content
Advertisement

VueJs – Conditional statement / filter on v-for results

So now i’m doing this to organise my results by category but if feel like this could be better:

<div><h2>Gloves</h2></div>
<div v-for="stash in stashes" :key="stash.id">
  <div v-for="item in stash.items" :key="item.id">
    <div v-if="item.extended.subcategories[0] === 'gloves'">
      {{ item.extended.baseType }}
    </div>
  </div>
</div>
<div><h2>Boots</h2></div>
<div v-for="stash in stashes" :key="stash.id2">
  <div v-for="item in stash.items" :key="item.id2">
    <div v-if="item.extended.subcategories[0] === 'belt'">
      {{ item.extended.baseType }}
    </div>
  </div>
</div>
<div><h2>Helmets</h2></div>
..
<div><h2>Weapons</h2></div>
..

If found this article doing this with a computed property and i feel like this should be the way but can’t get it to work (also because i need a argument for it to work this way i think?):

  computed: {
    filter(category) {
      return this.stashes.items.filter(a => a.extended.subcategories[0] === category);
    }
  }

and then something like this:

<div v-for="item in filter('gloves')" :key="item.id">
 ..
</div>

But yeah, it says i can’t pass a argument in that for loop like this so that is where i ended for now.

Anyone got an idea how to do this?

Stashes looks like this:

stashes: [
  {
    id: 1
    items: [{
      name: 'lorem',
      extended: {
        subcategories: ["gloves"]
      }
    }]
  },
  {
    id: 2
    items: [{
      name: 'ipsum',
      extended: {
        subcategories: ["boots"]
      }
    }]
  },
]

Advertisement

Answer

While using a method in the template might solve this, it’s not a good pattern because it causes the method to run every time the template is rerendered for any reason. Add another level of v-for:

<div v-for="category in categories" :key="category">
  <div><h2>{{ category }}</h2></div>
  <div v-for="stash in stashes" :key="stash.id">
    <div v-for="item in stash.items" :key="item.id">
      <div v-if="item.extended.subcategories[0] === category">
        {{ item.extended.baseType }}
      </div>
    </div>
  </div>
</div>

And create an array of categories like:

data() {
   return {
      categories: ['gloves','belt']
   }
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement