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

sanitizing user input in an AngularJS application

I created a feature in angular using ng-repeat <ul class="messages"> <li ng-repeat="e in enquiries"> <img src="/img/avatar.jpg" alt=""> <div> ...

Dealing with useEffect being invoked twice within strictMode for processes that should only execute once

React's useEffect function is being called twice in strict mode, causing issues that need to be addressed. Specifically, how can we ensure that certain effects are only run once? This dilemma has arisen in a next.js environment, where it is essential ...

Issues with routeparams are preventing ng-repeat from functioning properly, without any response or resolution

For my shoppingCart project, I am working on dynamically bringing data into views. I am using routeParams in template.html but facing an issue. The data is arriving normally as checked via ng-href="#/store/{{something.name}}/{{ child.name }}" but it isn&ap ...

jqgrid's date restriction is set to November 30th, 1999 at midnight

I have a table displaying DATETIME values. However, after editing the datetime value, it always changes to "1999-11-30 00:00:00", both in jqgrid and the database, regardless of the date entered. [Tue Mar 12 11:39:28 2013] [error] [client 171.43.1.4] PHP N ...

Issue with the positioning of the datepicker is not functioning properly

I'm currently facing an issue with the position of a date picker plugin from jquery. The search box on my website allows users to select a range of dates using the date picker, but when enabled, the date picker appears at the bottom left corner of the ...

Elegant rounded bordered sidebar design to highlight selected navigation items using HTML and CSS

I am looking to replicate the sidebar design displayed in the image below by using HTML and CSS. While I have successfully rounded the borders on the left side of a selected link, I am stuck when it comes to rounding the borders on the right side. ...

Extracting and retrieving information from a complex data structure obtained through an API call

Struggling with this one. Can't seem to locate a similar situation after searching extensively... My goal is to determine the author of each collection associated with a user. I wrote a function to fetch data from an API for a specific user, in this ...

The framework for structuring web applications using Javascript programming

While I have extensive experience in PHP and C# programming, my knowledge of Javascript is limited. When it comes to server side programming, MVC is my preferred method as it allows me to keep my code well-organized. However, when it comes to writing Java ...

What could be the reason my mat-form-field is not displaying the label?

I'm currently working on a project using Angular Material to build a web page. I am facing an issue with the mat-form-field component as the label is not displaying, and I can't figure out why. Any assistance would be greatly appreciated. Thank y ...

Using javascript to store HTML tags in a variable

Hey there, I have a quick question. Can someone help me figure out why this code isn't working? let plus = "+" + '<h1>'+"This is a heading"+'</h1>'; When I run the code, the output I get is: +<h1 ...

Removing custom scrollbars using jQuery from an element

Utilizing mCustomScrollbar with jQuery UI dialog boxes. When attempting to initialize mCsutomScrollbar on $(window).load as instructed, it fails because the dialogs are not yet visible. As a workaround, I've had to initiate mCsutomScrollbar on the op ...

The display function in Javascript has a tendency to work sporadically

I’ve been tasked with creating my own tic tac toe game through coding. While I am relatively new to programming, I have a strong passion for it. At the moment, I've set up a basic function to hide only the "O", leaving only the "X" visible on the gr ...

The concept of sharing states between components in Vuejs

Seeking advice on the optimal approach for implementing shared states between components in Vuejs. Consider scenario A: a web app displaying a modal with a boolean state show. This state should change when the modal's OK button is clicked, as well as ...

Switching Over to Burger Menu

I created a burger menu using HTML, CSS, and jQuery that switches from a full-width menu to a burger menu. However, I'm facing an issue with toggling the dropdown when the menu collapses. Here's my code: <!DOCTYPE html> <html> < ...

Tips for incorporating a Font Awesome icon <i> within a select dropdown and customizing its appearance

I am facing an issue while trying to insert an icon into a select option. The error message I received is: Warning: validateDOMNesting(...): cannot appear as a child of <option> To indicate that certain fields are required, I am using asterisk ic ...

Encountering CORS issue despite employing a CORS library

Encountering a CORS error while attempting to deploy my project on render using expressjs and react. The project functions smoothly on localhost, but changing the URLs to match the website results in this error: Access to XMLHttpRequest at 'https:// ...

Creating a unique carousel design using only CSS in Bootstrap

Trying to create a CSS effect to enhance Bootstrap, I noticed that it only works correctly when clicking the right arrow. Whenever I click the left one, nothing happens. I'm not sure where I made a mistake, can anyone help me spot it? Thanks in advanc ...

Enhance your web forms with jQuery Chosen's automatic formatting feature

Having trouble adding a feature to my multi-select input box using jQuery Chosen. The current functionality allows users to enter custom values not in the list. The new feature should automatically format numbers entered by users, for example: User input ...

What is the most efficient way to save a document in mongoose based on a specific user's

Is there a way to ensure that when saving a template, it is associated with the user id? I have added a reference to the templateSchema for the User. User.model.js var UserSchema = new mongoose.Schema({ _id: { type: String, required: true, index: {uniq ...

initiating AngularJS ng-model pipeline on blur event

My $parser function restricts the number of characters a user can enter: var maxLength = attrs['limit'] ? parseInt(attrs['limit']) : 11; function fromUser(inputText) { if (inputText) { if (inputText.length > max ...