Categories
Vue Answers

How to Toggle Classes on Click with Vue.js?

Spread the love

Sometimes, we want to toggle classes on click with Vue.js.

In this article, we’ll look at how to toggle classes on click with Vue.js.

Toggle Classes on Click with Vue.js

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *