Add a class to body when component is clicked?

2019-06-22 16:17发布

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.

5条回答
干净又极端
2楼-- · 2019-06-22 16:48

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.

查看更多
我想做一个坏孩纸
3楼-- · 2019-06-22 16:53

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楼-- · 2019-06-22 16:54

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.

查看更多
Deceive 欺骗
5楼-- · 2019-06-22 17:00

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' : ''
  }
}
查看更多
够拽才男人
6楼-- · 2019-06-22 17:05

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')
  }
}
查看更多
登录 后发表回答