DEV Community

Rémi
Rémi

Posted on • Edited on

4

Fix unexpected scroll jump - Vue Router

You may have noticed a breaking change in scroll behavior in modern browsers called scrollRestoration while using Vue Router.

It is an awesome feature that allows the browser to jump back to the previously saved scroll location with a JS script based routing.

Unfortunately, it conflicts with the Vue Router implemented methods scrollBehavior.

If you have no <transition/> on your <router-view/> you might not see any difference with the old behavior.
But if you are using it, especially leave transition, the page scroll jumps back to top at the start of the transition when you navigate to a new page.

The solution is to set scrollRestoration to manual, so the browser doesn't try to handle the behavior in your place.

if ('scrollRestoration' in window.history) {
  window.history.scrollRestoration = 'manual';
}

Source: History API: Scroll Restoration by Paul Lewis

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (3)

Collapse
 
anwar_nairi profile image
Anwar

Thank you so much Rémi, it helped me fix a bug when I was preventing route using next() when my LightGallery is opened (to make the back button act as a close action for this LightGallery), but the page would scroll to the top and not keeping the actual scroll. This is pure gold, the experience is now excellent great tips man!

Collapse
 
janpauldahlke profile image
jan paul

Have you adressed an issue in vue-router? and thx for the article

Collapse
 
uwutrinket profile image
Rémi • Edited

There is already a thread about the matter.
I think it might be still at discussion whether to implement because History.scrollRestoration is an experimental feature and might be removed.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay