The button's background color remains the same even after clicking on it

In my exploration of Vue.js, I decided to create a simple project to grasp the concept of class binding. I wanted to add functionality to each button component, so that when a button is clicked, it would change its color or background color to something other than black. However, I encountered an issue where clicking on the 'black mode' button did not change the button color as intended. Instead, it altered the background color outside of the button, which was not the desired behavior. Any assistance in resolving this issue would be greatly appreciated!

Here is my Button Component:

<template>
  <div>
    <div class="btn1">
      <button
        v-on="$listeners"
        :class="[dark ? 'dark' : 'light', 'baseButton']"
        class="btn"
      >
        {{ buttonText }}
      </button>
    </div>

  </div>
</template>

<script>
export default {
  name: "DynamicButton",

  props: {
    buttonText: {
      type: String,
      default: "label",
    },
    dark: {
      type: Boolean,
      default: false,
    },

    light: {
      type: Boolean,
      default: true,
    },
  },
};
</script>

<style scoped>
.baseButton {
  border-radius: 5px;
  border: none;
  padding: 10px;
  width: 200px;
  height: 30px;
}

.light {
  background: white;
  color: black;
  border: 1px solid lightgray;
}

.dark {
  background: black;
  color: white;
}

.btn {
  margin: 10px;
}
</style>

App.vue

<template>
  <div id="app">
 
    <DynamicButton
      buttonText="Dark Mode"
      :dark="true"
      @click="handleDarkMode"
      :style="{
        backgroundColor: active ? 'red' : 'blue',
      }"
    />
    <!-- default is the light mode so we dont have to pass any pops to it-->
    <DynamicButton buttonText="Light Mode" @click="handleLightMode" />
  </div>
</template>

<script>

import DynamicButton from "./components/DynamicButton.vue";
export default {
  name: "App",
  components: {
    DynamicButton,
  },

  props: {
    darkColorChange: {
      type: String,
      default: "",
    },
    lightColorChange: {
      type: String,
      default: "",
    },
  },

  data() {
    return {
      active: false,
    };
  },

  methods: {
    handleDarkMode() {
      console.log("Dark-mode clicked");
      // eslint-disable-next-line
      // this.darkColorChange.style.backgroundColor = "pink";
      this.active = !this.active;
    },

    handleLightMode() {
      console.log("Light-mode clicked");
    },
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

https://i.sstatic.net/OSPSo.png

Answer №1

Is this information useful?

<template>
  <div id="app">
    <img
      alt="Vue logo"
      src="./assets/logo.png"
    />
    <HelloWorld msg="Dynamic Button Component" />

    <DynamicButton
      buttonText="Dark Mode"
      :dark="true"
      @click="handleDarkMode"
      :color="active1 ? 'red' : 'blue'"
    />
    <!-- default is the light mode so we dont have to pass any pops to it-->
    <DynamicButton
      buttonText="Light Mode"
      @click="handleLightMode"
      :color="active2 ? this.color : '#16a085'"
    />
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";
import DynamicButton from "./components/DynamicButton.vue";

/**************************************************************************************
 * Watch: Vue.js - Dynamic & Reusable Button Component In Vue.js
 * https://www.youtube.com/watch?v=2Evw5h_1Ko8
 *
 * Render class bases on PROPS , dynamic class on button by binding class and pass an array
 *
 * Using the $listeners property, you can forward all event listeners on
 * the component to a specific child element with v-on="$listeners"
 *
 * check issues I had : https://stackoverflow.com/questions/74643295/button-background-color-doesnot-changes-when-clicked-on-it/74643605?noredirect=1#comment131784986_74643605
 ***************************************************************************************/

export default {
  name: "App",
  components: {
    HelloWorld,
    DynamicButton,
  },

  props: {
    // darkColorChange: {
    //   type: String,
    //   default: "",
    // },
    // lightColorChange: {
    //   type: String,
    //   default: "",
    // },
  },

  data() {
    return {
      active1: true,
      active2: true,
      color: "#3aa1b6",
    };
  },

  methods: {
    handleDarkMode() {
      console.log("Dark-mode clicked");
      // eslint-disable-next-line
      // this.darkColorChange.style.backgroundColor = "pink";
      this.active1 = !this.active1;
    },

    handleLightMode() {
      console.log("Light-mode clicked");
      this.active2 = !this.active2;
    },
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

You must include the active prop in the DynamicButton component and bind

:style="{
  backgroundColor: active ? 'red' : 'blue',
}"

to the button

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

Unable to properly structure data in JSON request

Trying to fill JSON request with data from phpsearch.php file (displayed below) <?php include "base.php"; $name = $_GET["name"]; $query = "SELECT lat, lng FROM markers WHERE name = '".$name."'"; $result = mysql_query($query); $json = array(); ...

Transmit data from the Windows Communication Foundation to JavaScript

Looking to invoke the WCF service through JavaScript, utilizing AJAX? Check out this resource: Calling WCF Services using jQuery Here's my query: Is there a method to retain some JavaScript-related data after making a request, and then transmit inf ...

An elegant approach to converting a JavaScript object containing key-value pairs into an array of objects, each with a single key-value pair

Essentially, I have an enum that represents different statuses status = {1: "new", 2: "working" ... } and my goal is to transform it into something like status = [{1: "new"}, {2: "working"} ...] in a way that is cl ...

Is the reordering of items in an Angular JS array causing a malfunction with the first item

It appears that there may be a syntax error present in my code. Within my controller, I have a set of 4 functions: adding a new item, deleting the current item, moving an item backward (up) in the array, and moving an item forward (down) in the array. Al ...

The dropdown menu is malfunctioning when accessed within the mobile view of a jQuery

Take a look at this code snippet on Fiddle: https://jsfiddle.net/rizwanali98601/ngofhc24/12/. The table below contains a dropdown inside a jQuery Datatable. When the button is clicked, an option is supposed to be added to the dropdown. However, in mobile ...

Execute Javascript to close the current window

When I have a link in page_a.php that opens in a new tab using target="_blank". <a href="page_b.php" target="_blank">Open Page B</a> In page B, there's a script to automatically close the tab/window when the user is no longer viewing it: ...

Creating an element in JavaScript with a designated ID is a

I'm working on creating a JavaScript array that holds 3 elements: var employees = [ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] To iter ...

Error: The JS Exception has not been handled, as it is stating that 'undefined' is not an object when evaluating 'global.performance.now' in react-native-tvOS

I am currently working on a React-Native-tvOs app and despite following all the instructions from the react-native-tvOs GitHub page, I keep encountering an error when running the default template app. Even after running the script provided on the GitHub re ...

aligning a form vertically in a container

<div class="parent"> <div class="left-child"> <img src="logo.jpg" alt="logo"> </div> <div class="right-child"> <form action="#"> <input type="text" value="search"> &l ...

Is it possible to reset the value of a current request attribute?

I designed a homepage that consists of a header, a sidebar, and a div tag. When a user clicks on the "register" button, Registration.jsp is loaded into the div tag. After successfully submitting the registration form, I want to redirect it back to the sa ...

The issue of an undefined Node.js variable post "await"

While I know similar questions have been asked before, I assure you that I've gone through them; however, I'm still facing a challenge. I have a simple code snippet to retrieve a token for a 3rd-party API service: let tok = ''; const g ...

Tips for integrating my Python random forest classifier in a web application built using HTML, Javascript, and Node.js

Greetings! I am currently in the process of creating a machine learning web application that requires the use of a random forest classifier. However, I am unsure of how to properly integrate the python code with it. Any guidance would be greatly apprecia ...

Tips on extracting the ID number prior to locating an element by its ID using Python Selenium

I am currently attempting to automate sending LinkedIn connection requests using Python with Selenium. However, I am facing an issue where the ember number value keeps changing every time I try to copy the id of the button. Sometimes it shows as #@id=" ...

Locate elements based on an array input in Mongoose

Define the Model: UserSchema = new Schema({ email: String, erp_user_id:String, isActive: { type: Boolean, 'default': true }, createdAt: { type: Date, 'default': Date.now } }); module.export ...

Tracking progress within an HTML table

I am facing an issue with a table that is designed to display progress bars for each method or task stored in the database. These progress bars are determined by two dates: the startDate and endDate. However, I have noticed that the progress bar only funct ...

Ways to acquire the reference of the parent component

Within my code, there is a parent component represented as: <Parent> <Child (click)=doSomething()></Child> </Parent> I am looking to establish a reference to the Parent component in order to pass it within a method that will trigg ...

Vue 3 Electron subcomponents and routes not displayed

Working on a project in Vue3 (v3.2.25) and Electron (v16.0.7), I have integrated vue-router4 to handle navigation within the application. During development, everything works perfectly as expected. However, when the application is built for production, the ...

Creating an HTML form that triggers a PHP script to send email upon submission via a Google Cloud Server

While running a php script to send an email upon form submission, I encountered an error message. Here are the details of the error: This XML file does not appear to have any style information associated with it. The document tree is shown below. &l ...

Looking for assistance with my MEAN stack To Do App project development

For a test at an enterprise, I have been tasked with creating a "to do APP" using Node js, Express, MongoDB & Angular Js. This is new territory for me as I have never worked with the MEAN Stack before but I am excited to explore it! The base project has al ...

Is there a way to alter visibility once a radio button has been selected?

I have a shape resembling a cube with 4 faces, all of which are currently visible. However, I would like to hide the other 3 faces when one face is showing. For example: I attempted setting the opacity of the other cube sides to 0 when the first radio but ...