When clicked the any of the buttons they are all turns active. So what i want is just the clicked one should be changed.
var vm = new Vue({
el: '#toolBtns',
data: {
isActive: false
},
computed: {
activeClass: function () {
return {
active: this.isActive
};
}
}
});
<div class="btn-group" role="group" id="toolBtns">
<button class="btn" type="button" @click="isActive = !isActive" :class="activeClass">Btn1</button>
<button class="btn" type="button" @click="isActive = !isActive" :class="activeClass">Btn2</button>
<button class="btn" type="button" @click="isActive = !isActive" :class="activeClass">Btn3</button></div>
You probably need a variable to find which button is currently selected. And you can use that variable to dynamically bind correct class: with : :class="{active: activeBtn === 'btn1' }"
.
Benefit of this approach is you have only one variable instead of array to save which button is currently selected, so you dont have to iterate on the array everytime you select a button.
var vm = new Vue({
el: '#toolBtns',
data: {
activeBtn:''
}
});
.active{
background-color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.js"></script>
<div id="toolBtns">
<div class="btn-group" role="group" id="toolBtns">
<button class="btn" type="button" @click="activeBtn = 'btn1'" :class="{active: activeBtn === 'btn1' }">Btn1</button>
<button class="btn" type="button" @click="activeBtn = 'btn2'" :class="{active: activeBtn === 'btn2' }">Btn2</button>
<button class="btn" type="button" @click="activeBtn = 'btn3'" :class="{active: activeBtn === 'btn3' }">Btn3</button></div>
</div>
See working fiddle here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With