Disable Page Scrolling When a Component Is Shown

May 9 2018 | By Taha Shashtari

Components like modal boxes, confirmation dialogs, or walkthrough tooltips often require the page scrolling to be disabled while they are open.

You can do that simply by setting the overflow of the <body> tag to hidden. But how can we make this behavior reusable for any component we want?

The answer, like in most cases, is to create a mixin for that. Let's call it noScrollMixin.

Creating the noScrollMixin

In your mixins directory, create a new file called noScrollMixin.js, then put this into it:

export default {
  mounted() {

  destroyed() {

The basic job of this mixin is to add no-scroll class to the <body> tag whenever the component is created and displayed. This class remains until the component is destroyed and removed from the DOM.

Let's write the css for the .no-scroll class

You can do this either in App.vue or in your main.css (I prefer the latter). In the end, it should look like this:

body.no-scroll {
  overflow: hidden;

Finally, you just need to use it

Like any other mixin, you just need to use it in the component you want, like this:

  import noScrollMixin from '@/mixins/noScrollMixin'
  export default {
    mixins: [noScrollMixin]

Subscribe to get my latest posts