Add a class to body when component is clicked?

I think I found an elegant “vue way” by using a watcher. By setting a data attribute i.e active and toggle this on click. You can add a watcher to check if it's true or false based on this add a class or some styling to the body.

I needed this for disabling the scroll on the body when a side panel was open. I use a prop instead of data but this shouldn't matter.

watch: {
  // whenever active changes, this function will run
  active: function () {
    document.body.style.overflow = this.active ? 'hidden' : ''
  }
}

Hope this helps:

In <template>

<button @click="toggleBodyClass('addClass', 'noScroll')">Add Class</button>
<button @click="toggleBodyClass('removeClass', 'noScroll')">Remove Class</button>

In <script>

methods: {
  toggleBodyClass(addRemoveClass, className) {
    const el = document.body;

    if (addRemoveClass === 'addClass') {
      el.classList.add(className);
    } else {
      el.classList.remove(className);
    }
  },
},

// Just in case you like to do it when page or component is mounted or destroyed.
mounted() {
  this.toggleBodyClass('addClass', 'yourClassName');
},
destroyed() {
  this.toggleBodyClass('removeClass', 'yourClassName');
}