I'm struggling to create filters in Vue that work with arrays of colors and objects called products. I also have a property called count to keep track of clicks:
data() {
return {
count: 0,
colors: [
'red',
'blue',
'yellow',
'green'
],
product:[
{
id: 1,
name: 'Dress shoes',
price: 5,
color:'red',
compare: null
},
{
id: 2,
name: 'Sports shoes',
price: 3,
color:'blue',
compare: null
},
{
id: 3,
name: 'Beach shoes',
price: 2,
color:'yellow',
compare: null
},
{
id: 4,
name: 'Slippers',
price: 1,
color:'green',
compare: null
}
]
}
}
Each color has its own filter button:
<button
class="color-picker"
v-for="color in colors"
@click="filterColors(color)">
{{ color }}
</button>
The function I'm working on to filter the colors is as follows:
filterColors(color) {
const filter = event.target || event.srcElement;
if (product.color !== color) {
if (this.count % 2 === 1) {
filter.classList.add("selected");
product.compare = false;
}
if (this.count % 2 === 0) {
filter.classList.remove("selected");
product.compare = true;
}
}
}
When compare
is set to false
, I add a hide-me
class to hide non-matching items when looping through the products array.
With this function, I am able to toggle the visibility of items using the class hide-me
.
My issue arises when I want to show items of multiple colors simultaneously. For example, clicking on the filter red
should display red items while keeping all other colored items visible. How can I achieve this with my current code?