Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a class to body when component is clicked?

I have a component in vue, I wish to toggle a class on the body on click.

How can I do this? Would I just have to use JS to target the body and add a class?

Or is there more of a vue way?

For context I need to add a no scroll class to the body to prevent scrolling for an overlay menu.

like image 790
panthro Avatar asked Mar 20 '17 15:03

panthro


2 Answers

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' : ''
  }
}
like image 71
Martin Risseeuw Avatar answered Oct 11 '22 14:10

Martin Risseeuw


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');
}
like image 36
Syed Avatar answered Oct 11 '22 12:10

Syed