Changing button colors in VueJs

I just started learning VueJS and I'm looking for an example on how to toggle colors between two buttons when they are clicked.

For instance, clicking the white button should change it to black while changing the other button to white, and vice versa.

Answer №1

If you're setting up your template:

<div class="button-wrapper" :class="{'active-one': state.oneIsActive}">
  <div class="button one" @click="toggleButton()" />
  <div class="button two" @click="toggleButton()" />
</div>

For your setup (You could also consider using a ref or other methods, depending on the version):

const state = reactive({
  oneIsActive: true,
});

function toggleButton() {
  state.oneIsActive = !state.oneIsActive;
}

Your SCSS style (might vary in pure CSS or SASS):

.button-wrapper {
  .one {
    background: white;
  }
  .two {
    background: black;
  }
  &:not(.active-one) {
    .one {
      background: black;
    }
    .two {
      background: white;
    }
  }
}

Answer №2

It appears that you are looking for a feature similar to a radio button group, where selecting one option reverts the color of the other.

To achieve this, the buttons must have shared state.

The implementation of sharing this state can vary, but in this instance, I recommend storing it in the parent component. The state could be managed using either the composition API or options API, with options possibly being more suitable depending on experience level.

<script>
export default {
  data() {
    return {
      selected: 0
    }
  },
}
</script>

<template>
  <button :class="{red:selected == 1}" @click="selected = 1">
    Button 1
  </button>
  
  <button :class="{red:selected == 2}" @click="selected = 2">
    Button 2
  </button>
</template>

<style>
  .red{
    background: red;
  }
</style>

example in vue SFC playground

Answer №3

Give this a shot :

new Vue({
  el: '#app',
  data: {
    buttons: [{
      name: 'Button A',
      bgColor: 'blue',
      color: 'white'
    }, {
      name: 'Button B',
      bgColor: 'green',
      color: 'black'
    }]
  },
  methods: {
    updateColor() {
      this.buttons.forEach(btn => {
        btn.bgColor = (btn.bgColor === 'blue') ? 'white' : (btn.bgColor === 'green') ? 'black' : btn.bgColor
        btn.color = (btn.color === 'white') ? 'black' : (btn.color === 'black') ? 'white' : btn.cColor
      });
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(b, index) in buttons" :key="index">
    <button
            :style="{ 'color': b.color, 'background-color': b.bgColor }"
            @click="updateColor">
      {{ b.name }}
    </button>
  </div>
</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 is the best way to transmit a JavaScript array to a servlet via AJAX?

Within a textarea, users input one or more email addresses separated by commas. Here is my JavaScript code: var emails = $("#emails").val().split(","); if (emails.length == 0) { window.alert("Please enter an email address."); ...

What is the best way to retrieve the value from a callback function within a promise?

Currently in my angularJS 4 application, I've implemented a cordova accelerometer plugin known as device motion for a specific purpose. This plugin includes a function named getAcceleration(successCallback,errorCallback). Consequently, I formulated a ...

The JavaScript require() function appears to be malfunctioning

Why am I encountering an error when trying to import a valid node_module? <script > var Twit = require('twit'); </script> Error: Uncaught ReferenceError: require is not defined I am puzzled as to why the require() function wor ...

Choose a file to upload from the given array

Can files be uploaded successfully by passing them as an Array of file objects through FormData? For example: var files_array = []; $.each($("input[type='file']")[0].files, function(i, file) { files_array.push(file); }); If I then push it to ...

Randomly selecting JavaScript with different likelihoods or percentages

I am currently running a Node.js process with setInterval that occurs every 100ms. Within this process, I have specific actions that I want to execute at varying intervals such as 2% of the time for action X and 10% of the time for action Y. Currently, my ...

What is the process for inserting JavaScript code into a ReactJS file?

I am brand new to ReactJS and JavaScript in general, and I'm attempting to make this simple JS code function within my ReactJS file. My objective is for the text to change to red when clicked. My attempts thus far include creating an external JS file ...

Changing dimensions of cube on stable base

I'm currently working on a project involving a dynamic cube that can be scaled in real time by adjusting its mesh. However, I'm facing a challenge in keeping the cube fixed to the floor while changing its height. Here's a snippet of the code ...

Even after trying to hide the legend in a Radar Chart using the configuration option `legend: {display: false}` in chart.js, the legend

Having trouble removing legend from Radar Chart in chart.js even when using legend: {display : false}. The code is being utilized and then displayed with HTML/JS. Here is the provided code snippet: var options5 = { type: 'radar', data: { ...

The AngularJS application is experiencing issues with routing back to the homepage using ui-router

I'm experiencing an issue with the ui-routing in my AngularJS app. It was working smoothly before, and I can't recall making any changes that might have impacted the routing. When I start debugging, the app loads correctly with the index navbar ...

What is the best way to eliminate the content of an element using javascript/typescript?

The progress bar I'm working with looks like this: <progress class="progress is-small" value="20" max="100">20%</progress> My goal is to use javascript to remove value="20", resulting in: <progre ...

Are XHR2 credential requests truly secure or easily faked?

I am working to determine the level of security provided by credentialed XHR2 requests. More precisely, can I verify that the request originated from a browser runtime environment, and not from a bot (such as a server-side program) that might be able to m ...

What are the recommended guidelines for organizing files in an NPM package for front-end development?

I am creating an NPM package for the front-end and I'm trying to figure out the optimal file structure. My package consists of a code.js file as well as a code.min.js file. Should these files be located in the root directory, a dist folder, or a src f ...

Having trouble maintaining the original events on a cloned element

My goal is to duplicate an element passed into a function and retain all associated events, including ones like $('.example').on('click', function(e) ... )} that are defined within the document ready. Here's what I'm trying: ...

Revamping the back button functionality to redirect to a different location

As I face a situation where I need to modify the browsing history dynamically, consider this scenario: I am currently on my page: http://mysite.example.com and then I navigate to another page by clicking a link: http://mysite.example.com/sports Upon clic ...

Can HTML be incorporated into a slot string within a Vue.js component?

I created a expander element with Vue.js and I'm trying to insert line breaks into some of the answers. How can I properly include line break tags in the slot string? Currently, they just display as regular text: <expander identifier="pricing" que ...

What causes the error message "TypeError: expect(...).not.toBeVisible is not a function" to be displayed while using jest-dom?

Regarding a previous inquiry on determining component visibility with Enzyme, I attempted to utilize the jest-dom library and specifically implement their toBeVisible function. Despite closely following the provided documentation, I encountered an issue w ...

Adding values dynamically to a select dropdown results in an empty field being inserted in the dropdown if the option includes spaces

I am facing an issue with my dropdown select feature, where the value is supposed to be added based on input from a text box. Everything works smoothly when the input in the text box consists of a single word without spaces. However, it fails to add anyth ...

Reproducing scripts in Google Tag Manager and React/Next applications

Currently, I am delving into the realm of Google Tag Manager and React + Next.js for the first time. This experience is proving to be quite intriguing as my familiarity with GTM is limited and my exposure to React is even less. Nonetheless, it's not a ...

Utilizing an 'onclick' confirmation function with PHP in HTML

Hey there, fellow members of the coding community! I'm currently working on a project where I need to create a menu that displays all clients with an option to delete them. When a user clicks on the delete button, I want a confirmation message to pop ...

JavaScript/DOM - What sets apart a "CSS Selector" from an attribute?

When it comes to excluding declarative event handlers: <a href='#' onclick=<handler> ... /> Is there a significant difference between an Attribute and a CSS Selector? For example, if I define my own attribute: <a href='#&a ...