Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 748
Angello L. Avatar asked Jun 24 '19 14:06

Angello L.


2 Answers

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'
    }
  }
})
like image 117
null Avatar answered Sep 21 '22 12:09

null


Modern Solution:

Prevent scrolling events on LightBox modal itself -

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

styling overflow: hidden might create some concerns.

such as;

  • Visibility of scrollbar
  • UI bounce by the effect of scrollbar visibility from hidden to auto
like image 40
Radical Edward Avatar answered Sep 20 '22 12:09

Radical Edward