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 hope you will find this helpful:
It allows to control your page body classes with vue-router. Wrote this when faced the similar issue.
Hope this helps:
In
<template>
In
<script>
I think that reactive binding to the body is generally frowned upon. See this forum response by Vue team member and the article he links to. This makes me think there is not a "vue way" to change the body's class when a component is clicked.
So I think, like you say, targeting the body with JS is the best option.
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.
i use a similar approach within a method (I call the setBodyClass() function from elsewhere as well, which is why it's wrapped in its own function: