[Vuejs]-Add class/style to active button in VueJS

0👍

Turns out it doesn’t work only on true and false.

For example:

My data indicated that the 1st button is active:

data() {
    return {
        activeBtn: 1,
    };
},

To bind the style to the active button, just set the style attribute to an if shorthand which checks the value of the data and changes the string-typed style.

<div class="btn1" v-bind:style="{ backgroundColor: activeBtn == 1 ? 'red' : 'green' }"></div>
<div class="btn2" v-bind:style="{ backgroundColor: activeBtn == 2 ? 'red' : 'green' }"></div>
<div class="btn3" v-bind:style="{ backgroundColor: activeBtn == 3 ? 'red' : 'green' }"></div>

Screenshot with the styling like in the code

Of course it’s better to not specify the styling but the class (for multiple style values)

Leave a comment