Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle of TWO classes in Vuejs

Tags:

vue.js

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?

like image 806
John Avatar asked Sep 11 '25 02:09

John


2 Answers

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
    }
  }
}
like image 87
fixmycode Avatar answered Sep 13 '25 18:09

fixmycode


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>
like image 41
Sebastian Scholl Avatar answered Sep 13 '25 19:09

Sebastian Scholl