Cort.Riv
Cort.Riv

Reputation: 45

Vue.js swap classs on click

I think this is a simple thing but I'm struggling on trying to understand how I can apply a class to a button and then change to another class after the click. I have multiple buttons that I would use as filters, the user would only be able to select one and only that button would be highlighted after selection. That I can do, but I can't seem to be able to remove the initial class to change the text color using v-bind. The initial class would be not active and after selection, highlight class would change the text color.

Here is the jsfiddle without the noactive class added, I just can't figure out what's the best solution.

JSFiddle

new Vue({
  el: '#vue',
  data: {
    selected: ''
  }
})
.highlight {
  color: green;
  font-size: 16px;
  border: 0;
  background: 0;
}


.notactive {
 color: grey;
 border: 0;
 background: 0;
 font-size: 14px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="vue">
  <button @click="selected = 1" :class="{highlight:selected == 1}">Button1</button>
  <button @click="selected = 2" :class="{highlight:selected == 2}">Button2</button>
  <button @click="selected = 3" :class="{highlight:selected == 3}">Button3</button>
</div>

Upvotes: 3

Views: 140

Answers (2)

chrismarx
chrismarx

Reputation: 12545

If I'm understanding your question, I believe the answer is as simple as extending what you have with another entry for the notactive class in your class binding:

<div id="vue">
 <button @click="selected = 1" :class="{highlight:selected == 1, notactive:selected !== 1}">Button1</button>
 <button @click="selected = 2" :class="{highlight:selected == 2, notactive:selected !== 2}">Button2</button>
 <button @click="selected = 3" :class="{highlight:selected == 3, notactive:selected !== 3}">Button3</button>
</div>

Here's the updated fiddle - https://jsfiddle.net/chrismarx/ptk247wz/

Upvotes: 0

GenericUser
GenericUser

Reputation: 3230

new Vue({
  el: '#vue',
  data: {
    selected: ''
  }
})
.highlight {
  color: green;
  font-size: 16px;
  border: 0;
  background: 0;
}

.notactive {
  color: grey;
  border: 0;
  background: 0;
  font-size: 14px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="vue">
  <button @click="selected = 1" :class="{highlight:selected == 1, notactive:selected !== 1}">Button1</button>
  <button @click="selected = 2" :class="{highlight:selected == 2, notactive:selected !== 2}">Button2</button>
  <button @click="selected = 3" :class="{highlight:selected == 3, notactive:selected !== 3}">Button3</button>
</div>

Upvotes: 1

Related Questions