How to toggle a class in Vue
In this tutorial, we are going to learn about how to dynamically toggle a class in Vue.js with the help of examples.
Toggling the classes
We can toggle a class dynamically in vue by passing an object to the v-bind:class
attribute.
In this example, we are toggling a class by clicking the Toggle
button.
<template>
<div id="app">
<div v-bind:class="{box: isActive}"></div> <button @click="handleToggle">Toggle</button> </div>
</template>
<script>
export default {
data() {
return {
isActive: true };
},
methods: {
handleToggle() {
this.isActive = !this.isActive; }
}
};
</script>
In the above code, we have passed {box: isActive}
to v-bind:class
attribute, where box
class will be added to div
element if the isActive
data property is true; otherwise it is removed.
If you click on a Toggle
button the box
class is removed, and toggle it again box
class is added.
You can also pass multiple classes like this.
<template>
<div id="app">
<div v-bind:class="{box: isActive, error: isError}"></div> <button @click="handleToggle">Toggle</button>
</div>
</template>
<script>
export default {
data() {
return {
isActive: true, isError: false };
},
methods: {
handleToggle() {
this.isActive = !this.isActive;
this.isError = !this.isError;
}
}
};
</script>
It will render:
<div class="box"></div>
After clicking the toggle button:
<div class="error"></div>
Using the Array syntax
Similarly, we can also toggle classes by passing an array to the v-bind:class
attribute.
<template>
<div id="app">
<div v-bind:class="[isActive ? box : '' ]"></div> <button @click="handleToggle">Toggle</button>
</div>
</template>
<script>
export default {
data() {
return {
isActive: true, };
},
methods: {
handleToggle() {
this.isActive = !this.isActive;
}
}
};
</script>
In the above code, we have used a ternary operator (?) inside the array, where box
class is added to div
element if an isActive
data property is true
, otherwise empty string ' '
is added.
You can also pass multiple classes by using an object syntax inside the array syntax.
<template>
<div id="app">
<div v-bind:class="[{box: isActive}, {error: isError} ]"></div> <button @click="handleToggle">Toggle</button>
</div>
</template>
<script>
export default {
data() {
return {
isActive: true, isError: false };
},
methods: {
handleToggle() {
this.isActive = !this.isActive;
}
}
};
</script>