Sometimes, we want to toggle classes on click with Vue.js with JavaScript.
In this article, we’ll look at how to toggle classes on click with Vue.js with JavaScript.
Toggle Classes on Click with Vue.js with JavaScript
We can toggle classes by passing an object into the :class
prop.
For instance, we write:
<template>
<div id="app">
<button @click="setActive">toggle class</button>
<p :class="{ active }">hello</p>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
active: false,
};
},
methods: {
setActive() {
this.active = !this.active;
},
},
};
</script>
<style scoped>
.active {
color: red;
}
</style>
We have the setActive
function that toggles the this.active
reactive property.
We set that as the value of the @click
directive to run it when we click the button.
Then we have :class=”{ active }”
to add the active
class when active
is true
.
And we set any element the active
class to have color red.
Therefore, when we click the toggle class button, we should see the red color on the text toggle on and off.
Conclusion
We can toggle classes by passing an object into the :class
prop.