Scroll To Top on Route change – Vue JS

Be it Vue JS, React, Angular or any other Single-Page application framework, one thing that is common in all of them is whenever a route changes the window’s scroll position stays the same. i.e. If you change the route, it will take you to the new page but it won’t scroll to the top of the page. Sigh.

For most of the people, this may not be a matter of concern but for few people it is. And today, I will tell you how you can make it work.

Vue JS offers various hooks during the life-cycle of a component/page such as created, beforeMount, mounted, updated, and more. But the one we’re looking for here is mounted which is called once the component has been rendered on the screen. We can utilize this hook and define it on the container or dumb component or the page component so once it has rendered on the screen it gets displayed from the top.

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

  // More code ...
}

The only downside of this approach is we need to define it for every page.

While the above approach gives you more control and I’d recommend using that in most cases but at times when you’re doing a small project or you don’t want to repeat yourself for all the components then you can go for the alternative approach given below.

Navigation Guards to the Rescue

Vue Router provides us flexibility of navigation guards which we can utilize as hooks in our scenario. Vue Router has various navigation guards but for our this specific problem we will be making use of beforeEach navigation guard which we will be defining in the global scope, once and for all.

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

  next();
});

Please note: Don’t forget to call next function in the navigation guard else a blank screen will be displayed.

That’s all for today. At last, if you liked the post and want to share the word with the community then feel free to comment down below and share your experience.