0

How can a Vue component button color be changed using a function? Bootstrap-vue is being used. In the code below, the tooltip is changed using a function, how can the same idea be applied to the button? Any help would be greatly appreciated.

Here is the Vue component:

<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>

1 Answer 1

2

Using Object Syntax

If you want to change the colour of the button based on checkbox1 prop, you can do this like:

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

This will set button colour to outline-primary if checkbox1 is true, else set it to outline-secondary colour. You can change the colour and logic based on your requirement.

Also, note that here :variant is simply a shortcut for v-bind:variant.

Using Computed Property

We can also bind to a computed property that returns an object. This is a common and powerful pattern:

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

and then create a computed property named getVariant like:

computed: {
  getVariant: function () {
    return {
      'outline-primary': this.checkbox1,
      'outline-secondary': !this.checkbox1
    }
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Is there a way to change the button color using a function, like what is being done with the toolltip?
Yes, we can also bind to a computed property that returns an object. This is a common and powerful pattern. I have updated the code.
Is it possible to change the button color with a regular function inside methods?
Yes, you can do it. Just put the computed prop to methods instead and the call it like :variant="getVariant()"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.