A Vue directive to lock the body from scrolling without stopping the target element from scrolling.
Uses the body-scroll-lock library (https://github.com/willmcpo/body-scroll-lock).
Works on mobile and tablet (iOS, Android) and desktop (Chrome, Firefox, Safari).
yarn add v-body-scroll-lock
npm i v-body-scroll-lock --save
In your main JS file first import this plugin
import VBodyScrollLock from 'v-body-scroll-lock'
Install the plugin
Vue.use(VBodyScrollLock)
Add v-body-scroll-lock
or v-bsl
(short version) to the element which you want to keep scrollable.
v-body-scroll-lock
and v-bsl
take a boolean
as an argument like v-body-scroll-lock="modalIsOpen"
If modalIsOpen
is true, body scroll lock will be applied to other elements except for the one which has v-body-scroll-lock="modalIsOpen"
For a more deep example checkout App.vue
in /src/App.vue
.
<template>
<div
v-body-scroll-lock="modalIsOpen"
v-show="modalIsOpen"
class="modal"
>
<p>This is a modal! I am scrollable while the body is not!</p>
<button @click="closeModal">Close modal</button>
</div>
</template>
<script>
export default {
name: 'modal',
data() {
return {
modalIsOpen: false,
}
},
methods: {
closeModal() {
this.$set(this, 'modalIsOpen', false)
},
openModal() {
this.$set(this, 'modalIsOpen', true)
}
}
}
</script>
Reserves the width of the scrollbar and prevents the unpleasant flickering effect that can occur when locking the body scroll.
More info here.
To enable the reserveScrollBarGap
option add :reserve-scroll-bar-gap
after v-body-scroll-lock
or v-bsl
.
Example: v-body-scroll-lock:reserve-scroll-bar-gap="modalIsOpen"
.
Issues can be created on the issues page.
To contribute, please make a pull request.