In this VueJS tutorial, we will learn how to toggle (add and remove) css classes of a HTML element when a button is clicked. This means when we click a button, css classes of the target HTML element will toggle.
HTML
We will create a target element and we will bind class attribute using v-bind.
class_status is a boolean data. When class_status is true, class name new_class will be added to the target element. And when class_status is false, the new_class will be removed.
1 | <div class="box" v-bind:class="{new_class:class_status}"></div> |
Button
Now we will create a button which when clicked will toggle the class of the target element.
1 | <button @click="class_status = !class_status ">Toggle Class</button> |
VueJS
1 2 3 4 5 6 | var vueApp = new Vue({ el: "#vue-element", data: { class_status: false, } }) |
Demo
Demo – Toggle class of an element when a button is clicked using VueJS