Add a class to body when component is clicked?

荒凉一梦 提交于 2020-01-03 08:39:20

问题


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.


回答1:


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.




回答2:


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' : ''
  }
}



回答3:


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');
}



回答4:


I hope you will find this helpful:

  • vue-body-class NPM
  • vue-body-class GitHub

It allows to control your page body classes with vue-router. Wrote this when faced the similar issue.




回答5:


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:

methods: {
  toggleMenu() {
    this.showMenu = !this.showMenu
    this.setBodyClass()
  },
  setBodyClass() {
    var body = document.body
    body.classList.toggle('open')
  }
}


来源:https://stackoverflow.com/questions/42906996/add-a-class-to-body-when-component-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!