How to disable / prevent scrolling in Vue

I encountered this problem when I was trying to implement an image modal component.
The correct behaviour should be:Modal open & disable keyboard mouse and scroll events except those that close the modal.
I tried a lot of ways, these ended up working ok:

Disabling scroll on PC

watch: {
      modalOpen: function (isOpen) {
        if (isOpen) {
          document.documentElement.style.overflow = 'hidden'
          // document.documentElement is the same as using document.querySelector('#root')
        } else {
          document.documentElement.style.overflow = 'auto'
        }
      }
    }

Disabling scroll on mobile

<div @touchmove="prevent>

methods: {
    prevent (event) {
        console.log('something happened')
        event.preventDefault()
        event.stopPropagation()
    }
}

Close modal when press Esc key

methods: {
    closeModalWithEsc (e) {
        if (e.keyCode === 27 && this.modalOpen) {
          this.modalOpen = false
        }
      }
},

created () {
      document.addEventListener('keydown', this.closeModalWithEsc)
    },
    destroyed () {
      document.removeEventListener('keydown', this.closeModalWithEsc)
    },

Close modal when click elsewhere

add @click="closeModal" to the modal overlay/background layer div

Leave a Reply

Your email address will not be published. Required fields are marked *