How to remove class in vue.js

Given you have a this element

<div id="randomDiv">
  <p :style="{backgroundColor:color}" @click="updateBackgroundColor(color)">{{obj.name}}</p>
</div>

the :style allows you to add a style to the element, in this case it is the backgroundColor style we are adding, it can be anything, and you can see that has a value of color which comes the Vue object bellow. This is initially set to yellow in the vm = new Vue() object. This object also has a function called updateBackgroundColor which carries out the update. The color is passed into this function from the @click in the element.

var obj = {
  "name": "Curtis",
}


var vm = new Vue({
  el: '#randomDiv',
  data: function (){
    return  {
        obj,
        color: 'yellow',
    }
  },
  methods: {
        updateBackgroundColor: function (color) {
        console.log(color);
          if(color === "yellow"){
            this.$set(this.$data, 'color', 'red');
          }
          else{
            this.$set(this.$data, 'color', 'yellow');
          }
        }
    }
});

i have also pasted this in JsFiddle for you to see.

[https://jsfiddle.net/ifelabolz/todqxteh/1044/][1]


From what is written in their documentation I'd say it something you should not do in your code.

Instead, your CSS classes should be bounded to properties and presence of a class should be determined by property value.

Example (from docs):

<div v-bind:class="{ active: isActive }"></div>

The above syntax means the presence of the active class will be determined by the truthiness of the data property isActive (if isActive IS true - class will be there).

You can have multiple classes toggled by having more fields in the object. In addition, the v-bind:class directive can also co-exist with the plain class attribute. So given the following template:

<div class="static"
     v-bind:class="{ active: isActive, 'text-danger': hasError }">
</div>

And the following data:

data: {
  isActive: true,
  hasError: false
}

It will render:

<div class="static active"></div>

When isActive or hasError changes, the class list will be updated accordingly. For example, if hasError becomes true, the class list will become static active text-danger.

I believe that's the right way to go :) Please check the documentation for more details.

If for some reason you need to remove a class you could add jQuery as a dependency to your app and use it (but it's not preferable).

Happy hacking :)