Switch up your Vue filters with ease

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?

Answer №1

There is no requirement to include an additional class.

Feel free to check out this custom example that I've created for you. Click here to view it.

Answer №2

One approach could be to create a dynamically filtering computed function that returns the desired data by applying it on the selectedColors array.

If possible, would you mind sharing a jsfiddle link for further analysis?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered when submitting form: Error identified as "Unexpected string expression without template curly in string"

As a novice in React.js, I am facing an issue where setState is not functioning properly when submitting a form. Any suggestions on how to resolve this problem? > class Home extends Component{ constructor(props){ > super(props) > ...

Looking to pass two distinct variables using a single props with v-if in Vue-JS. Any suggestions?

I am attempting to pass different data to my other component. Essentially, when my variable firstvalue is not null, I want to send firstvalue. Currently, this setup is functioning as expected. However, I now wish to send secondvalue if it is not null. < ...

Add information if the data does not exist, modify it if it does

My current project involves creating a TS3 bot using the Node.js Library from Multivit4min on GitHub. The purpose of this bot is to perform the following tasks: nick (txt) cldbid (int) clid (txt) lastChannel (int) Event #1 - When a client connects to a ...

Tips for automatically closing the Toggle Navigation feature in Vue JS when a user clicks outside of the navigation container

Is there a way to close the toggled navigation menu automatically when the user clicks outside of the navigation container? I have implemented two ul menus inside the navigation menu and would like the subNavActive, safNavAcitve, and repNavUl variables to ...

The functionality of Angular.js ajax and apply is experiencing technical difficulties

As I venture into the world of angular.js, I am facing a challenge with displaying the correct content on my website. The pages' content is fetched via AJAX (currently from static data, but eventually from a database). When I place a block with the ng ...

Alert: Jade has detected an unforeseen block called "scripts"

I created a jade file with the following content: extends layout block content h1= title p Hello and welcome to #{title} block scripts script(src='/socket.io/socket.io.js') script(src='/javascripts/client.js') But when I try ...

Struggling with sorting through props data based on specific search parameters in Vue 3

Currently, I am in the process of developing a client management system that is connected to a mySQL database. My goal is to filter the data retrieved from the database via an API using Laravel framework. Despite numerous attempts, I am encountering diffi ...

ReactJS how to prevent accordion from collapsing automatically

My custom accordion layout for the features needed in the site I am building is not working well with Jquery. How can I modify it to collapse properly? Specifically, I want it so that when I open number 2, number 1 will automatically close. I've trie ...

Issue with Vue.js when attempting to access router property: "Cannot read properties of undefined (reading 'router')" error

I recently started using Vue.js and I've built a simple form for users to input data, which is then stored using an API. Upon submission, I trigger the following function: setup(props, { emit }) { const blankData = { customer: '', ...

Error TS2304: Unable to locate identifier 'RTCErrorEvent'

I am currently working on a WebRTC application using Quasar, typescript and Vue. In my code snippet below, I am encountering an issue where I don't get any errors in WebStorm (as it uses the project's eslint config), and I can navigate to the def ...

Creating a pie chart with ExtJS using data from a JSON file

After successfully creating a pie chart using ExtJS with JSON values through AJAX calling, I encountered an issue when trying to do the same with JSON values retrieved from a file named myjson.json. Can anyone advise me on how to draw a pie chart by retrie ...

What is the reason behind the presence of an exclamation mark in my URL while using Angular?

Recently, I ventured into the MEAN stack and decided to follow some tutorials to get a better understanding. In my journey, I utilized npm-views from Angular in an attempt to redirect an HTML a tag to another HTML file. However, as I navigated to localhos ...

Having trouble incorporating autocomplete search results into an HTML table using Jquery, Ajax, and JSP

My current project involves an App that utilizes AJAX with jQuery to communicate with a Spring-boot REST controller. While the app is functional, I am facing difficulty in displaying the search results neatly within HTML tables. https://i.sstatic.net/7sw8 ...

JavaScript code to record the time when a client exits my website by clicking the X button in the top right corner and save it in my database

I need to record in the database the times when users enter and exit my site. Saving the entry time is not an issue, nor is saving the exit time by clicking my "log off" button. However, what about when a client exits by clicking the X in the right corner ...

How come it's so difficult to set the perspective camera to accurately display sizes in three js?

Currently, I am using Three Js to create a visual representation of a car. However, I am encountering an issue with the perspective camera that I can't seem to resolve. My goal is to make it appear more realistic by only showing the front of the car, ...

Introducing unnecessary DOM elements when displaying flash messages

When a user saves in my Rails application, it triggers an Ajax request to save the post and then runs the update.js.erb file. This file contains some jQuery code: $('body').append('<div class="message">Saved</div>'); Due t ...

Clicking on the div will redirect the page to one destination, while clicking on the anchor tag will redirect the page to a different destination

I have a div containing an anchor tag, like so: <div onclick="redirect to one location" style="height:200px;width:200px"><a href="http://www.google.com" >text</a></div> The div has dimensions of 200px by 200px and on click, it sho ...

Retrieving the value of a submit button within the `onSubmit` event handler in a React application

In my usual process, I typically handle the form submission by utilizing the onSubmit handler. <form onSubmit={e => { ... } }> <input ... /> <input ... /> <button type="submit">Save</button> </form> ...

Issue encountered when trying to access the webpage through a puppeteer connection

I am currently experimenting with web scraping using the puppeteer library to extract data from a Chrome page. I have managed to connect to an existing Chrome page in debugging mode by obtaining the ws URL and successfully establishing a connection. Here i ...

Extracting data types from strings in JavaScript

I have been developing a project using HTML and JavaScript where I need to extract two strings from the HTML script, pass them to JavaScript, and convert them into their respective variable types similar to using typeof. For instance, "true" shou ...