What is the best way to dynamically change the color of a Vue component button through a function?

Can anyone provide guidance on how to change the button color of a Vue component using a function while utilizing Bootstrap-vue? The code snippet below demonstrates how a tooltip can be altered through a function, but how can this concept be extended to modify the button color as well? Any assistance would be highly appreciated.

Below is the Vue component in question:

<template>
  <div class="text-center">
    <b-button v-b-tooltip.hover.right="tooltipText" variant="outline-primary" @click="userHandler(username)">
      <div v-bind:class="{ active: checkbox1 }">
        {{ username }}
      </div>
    </b-button>  
  </div>
</template>

<script>

import EventBus from '../eventBus.js'
export default {

    props: ['username', 'checkbox1'],

    data() {
      return {
         show: true,
         tooltipTextContent: 'block',
     }      
},

methods {


    userHandler(username) {

        EventBus.$emit('handleUser', username);  
    },


     tooltipText() {
          if (!this.checkbox1) {
            return this.tooltipTextContent
          } else {
            return `un${this.tooltipTextContent}`
          }
    }
},
} 

</script>
<style scoped>

.active {
    color: red;
}
</style>

Answer №1

Object Syntax for Button Color Change

To dynamically change the color of a button based on the state of the checkbox1 prop, you can use the following code:

<b-button 
   v-b-tooltip.hover.right="tooltipText" 
   :variant="{ 'outline-primary': checkbox1, 'outline-secondary': !checkbox1 }" 
   @click="userHandler(username)">

This code will set the button color to outline-primary when checkbox1 is true, and to outline-secondary otherwise. You can customize the colors and logic as needed.

Note that the usage of :variant is just a shorthand for v-bind:variant.

Computed Property Approach

Another approach is to bind to a computed property that returns an object:

<b-button 
   v-b-tooltip.hover.right="tooltipText" 
   :variant="getVariant" 
   @click="userHandler(username)">

You can create a computed property called getVariant with the following logic:

computed: {
  getVariant: function () {
    return {
      'outline-primary': this.checkbox1,
      'outline-secondary': !this.checkbox1
    }
  }
}

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

Easily choose multiple items at once by searching with react-select

I have implemented react-select to showcase a searchable drop-down list of items where users can select multiple items. The list is lengthy, and users often find it tedious to multi-select many items that match the same filter string. This is because each ...

The Vue router is unable to remove queries

Trying to remove a query parameter with a button click is my current challenge. Take for instance, my route: http://localhost:8080/#/myroute?dialog=1. When I press a button, it should erase the query part ?dialog=1. Here's how my click function appe ...

Is there a Webpack plugin available that can analyze the usage of a function exported in a static

Just to clarify, I am presenting this theoretical scenario on purpose, as it reflects a genuine issue that I need to solve and am uncertain if it's feasible. Imagine I have a JavaScript package named road-fetcher, containing a function called find wh ...

Exploring the functionality of useRoute within a composable in Vue

I am working on a file store/service.js and I am trying to incorporate a router. This is what I have attempted so far: import { useRoute } from 'vue-router'; const router = useRoute(); function exceptionHandler(error) { if (error.response.sta ...

Keeping data external to promises in protractor

In my angular app, I have a timeline feature that displays the names and descriptions of players. All player names are under the common class player-title.ng-binding, while all player descriptions share the class .player-description.ng-binding To retrieve ...

When working on a Vue project, the Navbar @click functionality seems to

Having trouble with my navbar search form <form action="" method="post" class="search"> <input type="text" name="" placeholder="поиск" class="input" v-model="alls ...

What is the process for transferring an object to a different file?

Currently, I am working on a web application using Node.js. In my project, I have two main files. The first one is Server.js, where I handle server actions such as going online. The second file contains a large object filled with data. I successfully impo ...

Animate the sliding of divs using the JavaScript animation function

I've designed some boxes that function similar to notifications, but now I want to smoothly slide them in from the left instead of just fading in. I know that I need to use .animate rather than .fadeIn to achieve this effect. The code snippet I&apos ...

Ways to retrieve textStatus beyond ajax boundaries

Do you know how to access the textStatus variable after an ajax call? I need to use this variable in an if condition. Can anyone provide assistance? $this->registerJs("colorArray = ['#ff4c4c','#32CD32']; $('.grooveTable&apo ...

Troubles encountered when populating the array within a Vue component

I am experiencing an issue with my ProductCard component where the addItem method is not successfully adding a new item to the array. <template> <div class="card"> <div v-for="item in TodoItems" :key="item.id ...

Tips for gradually increasing numerical values line by line

Plunker. After implementing the Plunker provided above, I noticed that the rowId is increasing with alphabets, as shown below: The component in the Plunker contains buttons labeled with +, ++, and -. When you press the + button, the rowId starts from the ...

The basic shapes in the scene are just out of sight

Sorry for the easy question, but I'm having trouble getting the BoxGeometry to show up in the scene. The red background is displaying correctly. var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(0, window.innerWidth / window.inn ...

creating pages within a freshly established subdirectory

Hello fellow developers! I could use some advice on an issue I'm facing. After creating a new folder in the pages directory, I am unable to render the pages live. Should I roll back and move all my templates back to the pages folder or is there anothe ...

Exploring the Junction of Vue-Router and Gsap ScrollTrigger

I'm encountering some issues with vue-router and the gsap scrolltrigger plugin. I have several vue components that utilize scrolltrigger, but when I navigate to a different page and then return to the page with the scrolltrigger effect, it fails to tr ...

Build a custom form for the purpose of exporting an HTML file

I am in search of a way to provide my users with various "feature" choices that will assist them in creating an HTML file for an email. I already have the code ready for each feature, but I want users to be able to select a feature (such as Hero Image Head ...

cross-domain ajax response

Imagine a unique scenario that will pique the interest of many developers. You have a JavaScript file and a PHP file - in the JS file, you've coded AJAX to send parameters via HTTP request to the PHP file and receive a response. Now, let's delve ...

Implementing conditional select options based on another select option in Vue.js

I am utilizing the library vue-search-select to manage the disabling of select options using isDisabled. Initially, the select option for specialty is disabled. My goal is to have it so that when hospital is selected, the specialty becomes disabled. Here ...

What is the most efficient method for sending query parameters through a URL in Vue.js with Axios?

My goal is to use Axios upon page load to retrieve a JSON object from the base URL. When a button is clicked, I want to append query parameters to the URL and fetch a different JSON object. For example, if the base URL is 'test.com', clicking the ...

Can you please identify the TypeScript type associated with the return value of the match() method in String prototype?

I need help with creating a Regex in JavaScript const pattern = /S(\d+)E(\d+)/; // identifying characters between "S" and "D" const result = 'SE01E09'.match(pattern); How should I declare the result variable? I have attempted various ...

Creating an image on an HTML canvas using RGB values

Looking for assistance on displaying an image using HTML Canvas with three 12x12 arrays containing R, G, and B values. I've seen Canvas demos showing how to draw lines, but nothing on using RGB arrays to create an image. Any tips or guidance would be ...