John
John

Reputation: 1297

Toggle of TWO classes in Vuejs

I have tried for a few hours to be able to add / remove TWO classes in Vue JS.

The doc examples only show how to toggle one.

I have a button, which I click that I want to change class to either: active toggle-on or toggle-off

I can do the "active" on and off, but I can not seem to be able to add/remove the second class.

The button looks like this:

<button v-on:click="toggleOnTop" id="toggleTopButton" v-bind:class="toggleActive"></button>

And my data:

data: () => ({
  toggleActive: {
    active: true,
    'toggle-on': true
  }
})

But it still only applies these two. How can I apply "toggle-off" in reverse?

Upvotes: 4

Views: 4348

Answers (2)

Sebastian Scholl
Sebastian Scholl

Reputation: 1095

Know too that you are able to pass a ternary operator to the class attribute when bound. For example:

<i :class="['fa', isHappy ? 'fa-smile' : 'fa-frown']"></i>

This just saves from having to repeatedly use the same boolean value in an object as suggested above, especially if you need to have multiple classes bound to each state - like so:

<i :class="['fa', isHappy ? 'fa-smile active' : 'fa-frown']"></i>

Upvotes: 2

fixmycode
fixmycode

Reputation: 8506

You may want to use a computed property or object syntax for this, lets say your method toggles a boolean in your data:

data () {
  return {
    isActive: false
  }
}
methods: {
  toggleOnTop () {
    this.isActive = !this.isActive
  }
}

The short form would be to add the following class binding:

< ... v-bind:class="{'active toggle-on': isActive, 'toggle-off': !isActive}">

Another approach would be to use a computed property that will set the classes as you want:

computed: {
  toggleActive () {
    return {
      'active': this.isActive,
      'toggle-on': this.isActive,
      'toggle-off': !this.isActive
    }
  }
}

Upvotes: 7

Related Questions