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.


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

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

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. 
Renat Galyamov

Want to share this with your friends?

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:

Write a Comment