Home » vue » How to add and remove class of the css when a check box is checked or not in vue?

How to add and remove class of the css when a check box is checked or not in vue?

Posted by: admin November 26, 2021 Leave a comment

Questions:

Suppose there is a checkbox I want to add and remove the class of css style when a checkbox is checked or unchecked. Below is the code I have used:-

 <template>
   <div class="app">
     <label><input type="checkbox" @click= "onchange($event)">add/remove class</label>
   </div>
</template>

 <script>
   export default {
     methods:{
       onchange($event){
         console.log($event)
       }
    }
  }
 </script>

How I will do my task by this that I have change my background color on checked and change the color when I unchecked the checkbox again.

Answers:

Create a CSS class (here: active), which gets bound to the HTML element (with v-bind:class) depending on a data variable (here: isActive).

new Vue({
  el: "#app",
  data: {
    isActive: false
  },
  methods: {
  	changeColor() {
      this.isActive = !this.isActive
    }
  }
})
.active {
  background-color: rgba(100,100,100,0.4);
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">

  <label v-bind:class="[{ 'active': isActive }]">
    <input type="checkbox" @click="changeColor()">
    add/remove class
  </label>
  
</div>