So now i’m doing this to organise my results by category but if feel like this could be better:
JavaScript
x
21
21
1
<div><h2>Gloves</h2></div>
2
<div v-for="stash in stashes" :key="stash.id">
3
<div v-for="item in stash.items" :key="item.id">
4
<div v-if="item.extended.subcategories[0] === 'gloves'">
5
{{ item.extended.baseType }}
6
</div>
7
</div>
8
</div>
9
<div><h2>Boots</h2></div>
10
<div v-for="stash in stashes" :key="stash.id2">
11
<div v-for="item in stash.items" :key="item.id2">
12
<div v-if="item.extended.subcategories[0] === 'belt'">
13
{{ item.extended.baseType }}
14
</div>
15
</div>
16
</div>
17
<div><h2>Helmets</h2></div>
18
..
19
<div><h2>Weapons</h2></div>
20
..
21
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?):
JavaScript
1
6
1
computed: {
2
filter(category) {
3
return this.stashes.items.filter(a => a.extended.subcategories[0] === category);
4
}
5
}
6
and then something like this:
JavaScript
1
4
1
<div v-for="item in filter('gloves')" :key="item.id">
2
..
3
</div>
4
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:
JavaScript
1
21
21
1
stashes: [
2
{
3
id: 1
4
items: [{
5
name: 'lorem',
6
extended: {
7
subcategories: ["gloves"]
8
}
9
}]
10
},
11
{
12
id: 2
13
items: [{
14
name: 'ipsum',
15
extended: {
16
subcategories: ["boots"]
17
}
18
}]
19
},
20
]
21
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
:
JavaScript
1
11
11
1
<div v-for="category in categories" :key="category">
2
<div><h2>{{ category }}</h2></div>
3
<div v-for="stash in stashes" :key="stash.id">
4
<div v-for="item in stash.items" :key="item.id">
5
<div v-if="item.extended.subcategories[0] === category">
6
{{ item.extended.baseType }}
7
</div>
8
</div>
9
</div>
10
</div>
11
And create an array of categories like:
JavaScript
1
6
1
data() {
2
return {
3
categories: ['gloves','belt']
4
}
5
}
6