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

Learn the process of transferring information through ajax while managing dependent drop-down menus

I have successfully set the initial value from the first combo-box and now I am looking to send the second variable from the second combo-box and receive it in the same PHP file. Below is the Ajax code snippet: $(document).ready(function(){ $(".rutas") ...

Having trouble locating the nivoslider IE8 jQuery bug, can't seem to track it

I am encountering an issue with the nivoslider script in IE8 and I am having trouble identifying what is causing it. The nivoslider works perfectly fine in all other browsers except for IE8. Any help or guidance on this matter would be greatly appreciated ...

Can we implement a variety of site designs based on the size of the window?

Utilizing media queries allows us to modify the CSS for various screen sizes. My inquiry is: can we switch to a completely different page layout (or View in MVC) when the window size, specifically when the width is less than 500? Assuming that the control ...

Ng-Repeat is generating empty list items

When I view this code in my browser, I see two list items, but there is no content displayed within them. The loop seems to be functioning correctly, but the items are not pulling any information from my list. I have revised my submission to accurately re ...

Displaying an array of JSON objects in ReactJS by parsing them

Recently, I've encountered an odd issue with my React App. I am attempting to parse a JSON object that includes arrays of data. The structure of the data looks something like this: {"Place":"San Francisco","Country":"USA", "Author":{"Name":"xyz", "Ti ...

Using jQuery each, the output is an undefined Object or HTMLElement

Using jQuery's each/getJSON to iterate through a data.json file, collect and format the data, and display it on the page within the #output div. The functionality is working correctly, except for the unexpected addition of [object HTMLElement] that a ...

Exploring the functionalities of can-deactivate without incorporating routing

I'm facing an issue with a parent component and multiple child components. The parent component contains a form, while each child component also has its own form. Unfortunately, all child components share the same route as the parent component and hav ...

Monitoring of access controls on Safari during uploads to S3

Safari 10.1.2 Encountering an issue intermittently while attempting to upload PDF files to S3 using a signed request with the Node aws-sdk. Despite working smoothly 90% of the time, have been pulling my hair out trying to resolve this problem. Could it be ...

What is the best way to test a React component that includes a Router, Redux, and two Higher Order Components using Jest and Enzyme?

I'm currently facing a challenge with this issue. I have a React Component that is linked to React Router 4 and Redux store, and it's wrapped by two HOCs. It may sound complicated, but that's how it was implemented. Here's the export st ...

Ways to showcase Material-UI Grid components without using cards

I initially used Material-UI grid items for spacing adjustments, but now they are displaying as cards. I would prefer them to be invisible like before, but the documentation doesn't provide a solution for this issue. Any assistance would be greatly ap ...

Unable to interpret the JSON reply from the server

I am currently developing a web application that sends data to a website, which then updates its database and returns a JSON array to replace my web app page. I am using AJAX for this query, but I am facing an issue with preventing the overwriting of my we ...

I am looking to insert a jQuery value or variable into the plugin options

How can I insert a jQuery value or variable into plugin options? This is my current script: $(document).ready(function() { // var bannerheight = 580; if ($(window).width() < 2100) { var bannerheight = 410; var opts = JSON.parse( ...

Unable to retrieve DOM value due to Vue.js template being inaccessible in Chromium, including from both DevTools and extensions

Currently, I’m developing a Chrome extension that needs to retrieve specific values from a webpage such as the item title. However, instead of fetching the actual title, it is reading a Vue.js template variable. Even when I use DevTools to inspect the p ...

Is there a way to keep the input field data in my form in next js persist even after the page refreshes?

I am currently developing a form in Next.js and I need the data to persist even after the page is refreshed or reloaded. Unfortunately, local storage does not work with Next.js, so I am exploring other alternatives. Every time I try to use local storage, ...

Cursor disabling effect in IE 11 causing interference with drop-down options on Twitter Bootstrap 3

Right above a disabled twitter bootstrap 'form-control' input element sits a drop-down list. <div> <select> <option> Option 1 </option> <option> Option 2 </option> <option> Op ...

"Transforming a Vue.js method within a component into a created method: A step-by-step guide

I am currently working on a vue.js codebase where a method within the component is triggered by onclick() However, I would like this method to automatically run when the page loads instead of being called by onclick. After reviewing the vue.js documentati ...

What could be causing ReactNative Dimensions component to display lower resolutions?

Currently, I am developing an application using React Native v0.45.1 and testing it on my S6 device. Despite setting a background image that matches the resolution of my phone, it appears excessively large on the screen, cutting off most of the content. T ...

Tips for configuring Visual Studio Code to utilize path mappings for handling automatic imports

In order to streamline my project and avoid messy paths, I am implementing absolute paths that will allow for consistent imports regardless of the file's location in the project tree. For this purpose, I made adjustments to the tsconfig.json: "paths ...

The 3D hover effect is malfunctioning in the Firefox browser

I've been working on a 3D hover effect and my code is functioning properly in Opera and Chrome, but for some reason it's not working in Firefox. I've even attempted using vendor prefixes, but to no avail. The strange thing is that when I rem ...

Solving runtime JavaScript attribute issues by deciphering TypeScript compiler notifications

Here is a code snippet I am currently working with: <div class="authentication-validation-message-container"> <ng-container *ngIf="email.invalid && (email.dirty || email.touched)"> <div class="validation-error-message" *ngIf=" ...