[Vuejs]-How can I add a class to body after clicking on a button in a component in VUEJS?

0👍

Add a method in your Vue component that creates the overlay and adds a no-scrollable class to body.

/**
 * Create the viewport overlay.
 */
createOverlay() {
  this.overlay = document.createElement('div')
  this.overlay.className = 'overlay'
  this.overlay.addEventListener('click', () => this.close())
  document.body.appendChild(this.overlay)
  document.body.classList.add('no-scrollable')
}

/**
 * Close the Modal when overlay is clicked.
 */
close() {
  // Trigger Modal Close Here
  this.overlay.removeEventListener('click', this.removeOverlay())
}

/**
 * Remove the overlay from the DOM.
 */
removeOverlay() {
  document.body.removeChild(this.overlay)
  document.body.classList.remove('no-scrollable')
}

CSS Styling:

.overlay {
  background: rgba(0, 0, 0, 0.6);
  height: 100%;
  left: 0;
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 1040;
}

body.no-scrollable {
  overflow: hidden;
}

0👍

what you can do is to bind the class to make it dynamic like this:<h1 :class="{ active: hello }">Show</h1> “active” is a class that you can style as you want and “hello” is just a property that you can set as false and then you can toggle, or just change to false in a button like this <button @click="hello = true">Hide title</button> in case you want to toggle use <button @click="hello =! hello">Hide title</button>

`:class="{ active: hello }"` the way it works is that active is only going to be valid if the value you pass after the `:` is true. 

here I left a link to sandbox.io so you can see an example:

https://codesandbox.io/s/confident-sun-h4ur9

0👍

I figured out that I can use the root element instead of the body element!
I could fix the problem of scrolling the background of a modal like below:

<button @click="modalShow">Show Modal</button>

modalShow() {
  // Trigger Modal Open Here
  this.showModal = true;
  this.$root.$el.classList.add('show-modal');
}
close() {
  // Trigger Modal Close Here
  this.showModal = false;
  this.$root.$el.classList.remove('show-modal');
}

for Css style:

.show-modal {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
}

This fixed my problem. I hope it can help you guys too 🙂

Leave a comment