Adding a class to a clicked button in Vue.js

A unique function of the code below is showcasing various products by brand. When a user clicks on a brand's button, it will display the corresponding products. This feature works seamlessly; however, I have implemented a filter on the brands' logos to appear grey until hover. Now, I wish for this filter to be removed when the button is pressed.

Currently, I have only managed to eliminate the filter from all brands, which defeats the purpose of highlighting the selected button. How can I assign the 'active' class to only one button, the one that the user is clicking?

HTML:

<template>
  <div>
    <div class="buttonBrand">
      <button v-for="(element, index) in brand"   :key="index" :class='{buttonActive : isActive  }' @click="changeBrand(index)">
        <img v-bind:src="element.imageBrand" alt />
      </button>
    </div>
    <div class="product-wrapper">
      <single-product-new v-for="(element,index) in object" :key="index" :element="element" />
    </div>
  </div>
</template>

SCSS:

.buttonBrand {
    display: flex;

    button {
        margin: 25px auto;
        justify-content: space-between;
        img {
           filter: grayscale(100%) contrast(30%);
        }
        img:hover {
            filter: none;

        }

        .is-active {
            img {
                filter: none;

            }
          }
    }
    .buttonActive {
        img {
            filter: none;
        }
    }

}

JavaScript:


const singleProductNew = () => import("../singleProductNew/singleProductNew.vue");

export default {
    // COMPONENTS
    components: {
        singleProductNew
    },

    props: {

    },



    // DATA
    data() {
        return {
            isActive: false,
            object: null,
            brand: [{
                title: 'lg',
                imageBrand: "/img/lg.png",
                products: [{
                    volume: "123",
                    energyseal: "A++",
                    dimensions: "123",
                    wattage: "123",
                    color: [{
                        price: "123",
                        fee: "111",
                        reference: "asdasdasda",
                        colorName: "white",
                        availability: "yes",
                        image: '/img/hot_1.png'

                    },
                    {
                        price: "321",
                        fee: "222",
                        reference: "23123",
                        colorName: "gray",
                        availability: "no",
                        image: '/img/hot_1_b.png'
                    }
                    ]
                },
                {
                    volume: "123",
                    energyseal: "A++",
                    dimensions: "123",
                    wattage: "123",
                    color: [{
                        price: "123",
                        fee: "333",
                        reference: "123",
                        colorName: "gray",
                        availability: "yes",
                        price: "123",
                        image: '/img/hot_2.png'

                    },]
                }

                ],


            },
            {
                title: 'samsung',
                imageBrand: "/img/samsung.png",
                products: [{
                    volume: "333",
                    energyseal: "A++",
                    dimensions: "123",
                    wattage: "123",
                    color: [{
                        price: "888",
                        fee: "77",
                        reference: "123",
                        colorName: "white",
                        availability: "yes",
                        image: '/img/sam_1.png'

                    },
                    {
                        price: "321",
                        fee: "123",
                        reference: "23123",
                        colorName: "gray",
                        availability: "no",
                        image: '/img/sam_1_b.png'
                    }
                    ]
                },
                {
                    volume: "1123",
                    energyseal: "A++",
                    dimensions: "123",
                    wattage: "123",
                    color: [{
                        price: "123",
                        fee: "123",
                        reference: "123",
                        colorName: "gray",
                        availability: "yes",
                        price: "123",
                        image: '/img/sam_2.png'
                    },]
                }
                ],
            },
            ]
        }
    },

    mounted() {
        this.object = this.brand[0].products;

    },
    // METHODS
    methods: {
        changeBrand(index) {
            this.object = this.brand[index].products;
            if(this.isActive){
                this.isActive = false;
              }else{
                this.isActive = true;
              }


        }

    }
}

In addition to the mentioned details, the buttonActive class is currently applied to all buttons, whereas I aim to apply it solely to the clicked button.

Answer №1

To enhance the functionality, consider introducing a new data object property named currentIndex and ensure it gets updated to the index of the clicked button:

// DATA
data() {
  return {
    currentIndex: -1,
    isActive: false,
       ...

Within the template, bind the class in this manner

:class='{buttonActive : (index==currentIndex) }'
:

<div class="buttonBrand">
  <button v-for="(element, index) in brand" :key="index" :class='{buttonActive : (index==currentIndex) }' @click="changeBrand(index)">
    <img v-bind:src="element.imageBrand" alt />
  </button>
</div>

Methods :

changeBrand(index) {
    this.object = this.brand[index].products;
    this.currentIndex = index;
}

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

Has anybody successfully implemented the danfojs-node package on an Apple M1 chip?

I encountered an issue when trying to use danfojs-node on a Mac with an M1 chip - it kept crashing due to TensorFlow. I'm curious if anyone has managed to successfully integrate the npm package from this link (https://www.npmjs.com/package/danfojs-nod ...

Which is better: Starting with rows or columns in Bootstrap 4 layout design?

Many Bootstrap 4 grid layout demos feature columns within rows, but is it considered improper to have rows within columns? For example: <div class="col col-md-6"> <div class="row"> </div> </div> ...

You need to pass a function as the first parameter when using passport-local-mongoose as a schema plugin

I've been struggling with implementing passport-local-mongoose in my server. I followed a tutorial video but encountered an issue that wasn't addressed in the video - even though my database is connected to mongodbatlas. The error message "First ...

A distinct handler function designed for a dynamically generated form

I have 3 MaterialUI TextFields that are rendered n number of times based on user input (stored in a variable named groupMembersCount) in a functional ReactJS component using the useState hook: const [groupDetails, setGroupDetails] = React.useState([ { ...

Verify if a certain value exists in an array while using ng-if inside ng-repeat

Currently, I have a loop using ng-repeat that goes through a list of wines obtained from an API. Alongside this, there is an array variable containing all the IDs of wines that have been marked as favorites and retrieved from the database. My goal is to sh ...

Learn the process of utilizing Apple Pay on VJs using Stripe!

I followed the instructions at https://stripe.com/docs/stripe-js/elements/payment-request-button to set up Apple Pay for the web and Stripe. I've completed the initial steps, including domain verification, but I'm encountering an issue with the p ...

Blurry black-and-white picture

As a beginner in HTML and CSS, I am still learning. I have a challenge where I have two images and when one of them is hovered over, it should increase in size and display text. Additionally, I want the image that is not in focus to appear in grayscale. Wh ...

Preventing Event Bubbling in Polymer 1.5 for iOS When Using iron-pages

Our single-page app utilizes iron pages and express-router for navigation. While it functions flawlessly on browsers and Android devices, we've encountered a bug when using iOS. The issue arises when switching pages by clicking a button. If the button ...

In Vue.js, is it possible to nest a <tr> tag inside another <tr> tag?

I've been working on a dynamic table in vue.js, using the code snippet below: <template> <tr class="left-align" v-for="(item,index) in itemList" :key="index.id"> <td>{{item.items}}</td> ...

When attempting to trigger a function by clicking a button in Angular 8 using HTTP POST, nothing is happening as

I've been struggling to send a POST request to the server with form data using Observables, promises, and xmlhttprequest in the latest Angular with Ionic. It's driving me crazy because either I call the function right at the start and the POST wo ...

The data type "100%" cannot be assigned to a number type in the kendo-grid-column

I need the columns in the grid to have a width of 100%. <kendo-grid-column field="id" title="id" [width]="'100%'"> </kendo-grid-column> However, when I hover over the code, I get this message: The value "100%" cannot be ...

Transform a PDF document into a Google Doc utilizing the capabilities of the Google Drive API version 3

I successfully uploaded a PDF file to Google Drive using a node server. However, I am struggling to find a way to convert it to a Google Doc format so that it can be downloaded later as a DOCX document. Here is the code snippet I've been working with ...

Having issues with the $addToSet method in my MongoDB API implementation

Despite searching through various topics, I couldn't find a solution to my specific problem. In an effort to enhance my JavaScript skills, I embarked on creating a quote generator. I successfully developed the API and frontend components. However, c ...

Using Slick Carousel alongside Browserify for a seamless integration with CDN jQuery

Despite browsing through all the responses on SO regarding this issue, I still haven't found a solution. In my project, I have jQuery loaded via Google CDN. Additionally, I am using babelify, browserify and browserify-shim in an attempt to make slick ...

Expanding the size of a text area input within a form using CSS and

How can I adjust the size of the text area in the Comment section to match the full width of the section, starting from the beginning instead of the middle? You can find the code here. HTML <body bgcolor="#00BCD4"> <div> <h1>Co ...

Is there a way to use JavaScript to automatically open a URL at regular intervals?

List of URLs in JavaScript: var websites = ['https://www.google.com', 'https://www.msn.com', 'https://stackoverflow.com']; I have an array containing multiple website URLs. My goal is to open each URL in a new tab or window e ...

Struggling to transmit data to material dialog in Angular2+

I am facing an issue with my Material Dialog not working properly. Can anyone point out what I might be missing? product-thumbnail.ts I will use this to trigger the dialog export class ProductThumbnailComponent implements OnInit { @Input() product: Pr ...

Ensuring all ajax calls have completed before proceeding using selenium webdriverjs

In my attempt to create a function that can wait for all active (jQuery) ajax calls to complete in a Selenium WebdriverJS test environment, I am faced with challenges. My current approach involves integrating the following components: Implementing WebDri ...

Navigating State as a Fresh Path in Ionic Framework using Angular UI-Router

I am currently using the Ionic Framework along with its AngularJS UI-Router and $stateProvider to manage different views within my application. However, I am facing challenges in specifying to the $stateProvider that I have multiple "Main Views", each of ...

Link the Material-ui ToggleButtonGroup with redux-form

I'm currently facing a challenge with connecting the material-ui ToggleButtonGroup to Redux form. The issue seems to be occurring in my code snippet below: <Field name='operator' component={FormToggleButtonGroup} > <ToggleButt ...