How to dynamically change the color of a button in a list in Vue.js when it is clicked

I am working on a dynamic list of buttons that are populated using an array of objects:

          <div
            class="form-inline"
            v-for="(genre, index) in genreArray"
            :key="index"
          >
            <button class="btn m-1" type="button" @click="genreButton(genre, index)" 
                :class="[
                  { 'clicked': clicked}
                ]"
            >
              {{ genre.name }}
            </button>
          </div>

The format of the array is as follows:

genreButton=[{
  id='1234'
  name='buttonOne'
},
//and many more objects with same key and different values
]

I am attempting to change the color of only the button that is clicked by adding a specific class to it:

data(){
  return {
    clicked: false  
  }
},
methods:{
  genreButton(genre, index){
    this.clicked = !this.clicked
  }
}

Here is the CSS I am using for changing the color:

.clicked{
  background-color= red;
}

However, I am facing an issue where all buttons change color when one is clicked. How can I ensure that ONLY the clicked button changes color?

Answer №1

Within this context, the clicked property exists at the component level and is shared among all buttons nested within.

An alternative approach would involve assigning a unique clicked property to each button in the genreButton array:

genreButton=[
  {
    id:'1234'
    name:'buttonOne'
    clicked: false,
  },
  //...
]

Yet, a more refined solution could entail creating a dedicated button component with an internal clicked property.

<template>
  <button 
    class="btn m-1" 
    type="button" 
    @click="clicked = !clicked" 
    :class="[ { 'clicked': clicked} ]" >
    {{ genre.name }}
  </button>
</template>

<script>
export default {
  name: 'CustomButton',
  props: {
    genre: Object,
  },
  data: () => ({
    clicked: false,
  })
}
</script>

<style scoped>
.clicked{
  background-color= red;
}
</style>

You can then utilize the button component like this:

<div
  class="form-inline"
  v-for="(genre, index) in genreArray"
  :key="index" >
  <CustomButton :genre="genre" />
  
</div>

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

What steps can I take to make sure my JavaScript code accurately calculates numbers without resulting in undefined or NaN values?

I'm having an issue with my javascript code for a simple interest calculator. Every time I try to calculate the amount, it keeps returning NaN. It seems like the code is treating the + as if I'm trying to concatenate strings, and I'm not sur ...

foreverjs neglects to log the child process's console.log output to any log files

I currently have a nodejs server running that fetches data using the setInterval function every x seconds. Here is a snippet of that part of the app: startPolling () { debug('Snmp poller started'); timers.setInterval( this.poll( ...

Can all date fields with identical dates be updated simultaneously?

Is it feasible for a user to modify the date in one input and have that change reflected in all other inputs with the same 'initial' attribute? I've made an attempt at it, but haven't quite cracked the code on how to achieve this... ...

Prolong the duration before the submenu closes on a div-based css menu

I have created a unique horizontal menu using DIVs without the use of ul and li lists. Currently, I am searching for a way to delay the collapse of the submenus when the mouse moves out. I don't mind if the solution involves JavaScript, jQuery, or CSS ...

Changing the color of an element on click using jQuery's .css() method,

There is a table and I am using fadeToggle on the list to hide and show the table. The background of the list is green color, but I want to change the list color when hiding the table and revert it back to green when clicking to show the table. Unfortunate ...

Unable to retrieve obj after using $location.url

I am working with two different views. In the first view, I call a function from the admin controller using AngularJS: <a ng-click="updateAdmin(admin)">update</a> The code in the admin controller looks like this: $scope.updateAdmin = functio ...

Transforming the appearance of the menu element in Vue using transitions

In my Vue app, I have this SCSS code that I'm using to create a smooth transition effect from the left for a menu when the isVisible property is set to true. However, I am encountering an issue where the transition defined does not apply and the menu ...

Struggling to locate the correct path for the CSS file in Express and Handlebars

As part of a student exercise, I am attempting to access an API containing information about presidents and style them using CSS. However, I am facing issues with linking the style.css file. I have tried various methods to change the path and public path ...

Sending JSON data back to the server using KeyValuePair in C#

My goal is to send my JSON list back to the POST method (EditCompanyReportField) on the C# server side. The related parameter (fieldSorted) in my method is an array object, but the values are not being passed through. I have a few question marks regarding ...

Modify the image inside a div when hovering

How can I create a product card that displays thumbnails of images when hovered over, and changes the main image to the thumbnail image? My current challenge is getting this functionality to work individually for each card on an e-commerce site. Currently, ...

Is today within the current week? Utilizing Moment JS for time tracking

There is a problem that I am facing. Can you assist me in determining whether the day falls within the current week? I am currently developing a weather forecast service and need to validate if a given day is within the current week. The only clue I have ...

Developing a Single Page Application using Express

I'm currently working on developing a SPA using the React/Redux/Express stack. The current state of my server setup is as follows: import express from 'express' import dotenv from 'dotenv' import path from 'path' dotenv ...

Blazor: Passing a CSS class as a parameter to a child component

Is there a way to ensure css isolation works properly when passing a class as an argument to a child component? In the following code snippet, I anticipated the child component would display in blue, but that's not happening. Parent.razor <div cla ...

The <mat-radio-button> component does not have a value accessor specified

When working with HTML and Angular, I encountered the following issue: <mat-radio-group> <mat-radio-button [(ngModel)]="searchType"> And (Narrower search) </mat-radio-button> <mat-radio-button [(ngModel)]="searchType"&g ...

Obtaining the value of a command argument with JavaScript in ASP.NET

<asp:LinkButton ID="lnkprogress" runat="server" class="label label-info" BackColor="#589FC2" CommandArgument='<%#Eval("BookingId")%>' OnClientClick="jk();" >In progress</asp:LinkButton> This LinkButton is present in a repeat ...

Code in jQuery or JavaScript to retrieve precise node information for the currently selected form field, text, or image on a webpage

Looking to retrieve specific information about the item that has been clicked on a web page using jquery. The clickable item could be a form element (like a checkbox, text box, or text area) or a section of text within a paragraph, div, list, or image... ...

Having trouble decoding audio data in JavaScript Web Audio?

I'm attempting to utilize the Web Audio API in JavaScript to upload a sound into a buffer and play it. However, I am encountering an issue where it does not work and an error message is displayed: Uncaught TypeError: Failed to set the 'buffer&ap ...

What is the best method for inserting the HTML content from a specific div into a textarea?

Everything seems to be working fine, but once I insert the HTML into the textarea, an issue arises where the div gets wrapped within another div, causing the layout to break. var urls = []; $('body').on('click', '.btn_video&apos ...

Is it possible to maintain a fixed footer while utilizing async/ajax functions?

Looking for a reliable solution to have a fixed footer that adjusts based on the page content? I've tested multiple samples, but they all fall short when it comes to incorporating AJAX elements. Is there a fixed footer out there that truly works seaml ...

What is the process for logging in or authenticating before running tests with pa11y-ci?

Is there a way to authenticate users and test pages using pa11y-ci? When running pa11y-ci, I typically use this command: pa11y-ci --sitemap http://www.example.com/sitemap.xml --sitemap-find https --sitemap-replace http I came across some helpful informa ...