Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a specific (this) button class when click on. Using Vue.js 2.0

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>
like image 430
radeveloper Avatar asked Feb 06 '17 07:02

radeveloper


1 Answers

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.

like image 86
Saurabh Avatar answered Sep 22 '22 05:09

Saurabh