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.
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With