Prevent Scrolling in VueJS

22,788

Solution 1

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

Solution 2

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
Share:
22,788
Angello L.
Author by

Angello L.

Updated on July 16, 2022

Comments

  • Angello L.
    Angello L. almost 2 years

    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.

  • Angello L.
    Angello L. almost 5 years
    Syntax Error: SyntaxError: /Users/angello.lazar/Desktop/sdc-social-album-widget/src/App‌​.vue: Unexpected token, expected "," (128:35) 126 | }, 127 | watch: { > 128 | isModalVisible: preventScroll(){
  • Angello L.
    Angello L. almost 5 years
    That makes sense - thanks. But, not sure why I am receiving this error...
  • Angello L.
    Angello L. almost 5 years
    Figured it out! Thanks for the help!
  • Admin
    Admin over 4 years
    thats not work on ios devices. U need fixed content and wach page scroll posotion, then add negative position top to your fixed wrap. after, when scroll turn on, u need scrollTop() on js to prev position.
  • Hosein
    Hosein over 2 years
    @touchmove.prevent worked for me in mobile. I liked it