Vue.js scroll to top on route change

in Code Write a comment

In this tutorial you’ll learn how to make the new page open at the top of the page.

Single Page Applications (or SAP), whether it’s in Vue.js, React or Angular, have one thing in common – they open new pages in the same scroll position.

If you change the route, it will take you to the new page but it won’t scroll to the top of the page.

Vue.js example

To open a new page at the top you can add this line of code to your mounted() object:

mounted () {
  window.scrollTo(0, 0)
}

You’ll need to manually add it to every component.

Bonus

Alternatively, you can add it to all components at once by tweaking your router file.

router.beforeEach((to, from, next) => {
  window.scrollTo(0, 0)
  // ...
})

Hi, I'm Renat 👋

 


I wouldn’t suggest the second option, because believe it or not in some scenarios you’d like to be in full control over this feature.

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vue-js-scroll-top

PS: Make sure you check other Vue.js tutorials, e.g. how to make a GET request in Vue.jshow to import a component inside another component in Vue.js.

Incoming search terms:

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment

9 Comments

  1. Hey Renat,

    although I have a view that will scrollTo(0,0) on mounted – I would like to return to the ‘original’ scroll position when hitting back. Do you know how to pull that off?

    Thanks!

    • Hey Geffrey,

      Sure, you can add a scrollBehaviour function to your router instance to return to the original scroll position:

      scrollBehavior (to, from, savedPosition) {
        if (savedPosition) {
          return savedPosition
        } else {
          return { x: 0, y: 0 }
        }
      }

      Let me know if it works for you!

  2. Thanks bro, you’ve helped me a lot! It works for me just fine.
    In the syntax do we have to add some ” ; ” or ” , ” when we already have something in the Mounted structure?

    • You’re very welcome, bro!
      No, you do need to add commas. Semicolons “;” can be optional, it depends on your linter