Angello L.
Angello L.

Reputation: 111

Prevent Scrolling in VueJS

I am trying to prevent scrolling only when the lightbox component is open, but cannot seem to do so. I hope to not use any outside libraries or plug-ins to do this.

My App.vue contains the "LightBox" component, so I am assuming the prevent scrolling function should live in the App.vue as well. App.vue snippet:

<template>
  <div class="SocialAlbumWidget">
    <div v-if="isModalVisible && media[activeIndex]">
      <LightBox
        ...
      />

I currently have a "showModal ()" function in the "methods" section, so was thinking of passing that through another function.

Methods:

mothods: {
...
showModal () {
  this.isModalVisible = true
},
closeModal () {
  this.isModalVisible = false
}

I expect the body to have scroll when the"Lightbox" component is closed and disabled when the "Lightbox" component is open. Thanks! Let me know what other code would be useful.

Upvotes: 9

Views: 44511

Answers (2)

Ranjeet Eppakayala
Ranjeet Eppakayala

Reputation: 3058

Prevent scrolling events on LightBox modal itself -

<LightBox
 @wheel.prevent
 @touchmove.prevent
 @scroll.prevent
/>

style overflow: hidden might create some concerns.

such as;

  • Visibility of scrollbar
  • UI bounce w.e.f overflow toggle

Upvotes: 18

Bruno Francisco
Bruno Francisco

Reputation: 4240

You could use a watcher to react to changes in isModalVisible and disable the scrolling function by using style="overflow: hidden".

Something along these lines:

// HTML
<btn @click="dialog = !dialog" >Click Me </btn>

// JS
new Vue({
  el: '#app',
  data () {
    return {
      dialog: false,
    }
  },
  watch: {
    isModalVisible: function() {
      if(this.isModalVisible){
        document.documentElement.style.overflow = 'hidden'
        return
      }

      document.documentElement.style.overflow = 'auto'
    }
  }
})

Upvotes: 20

Related Questions