Vue Router save scroll position on a route and go back to that position when navigating back?

Viewed 11377

I'm using Vue Router and scrollBehavior and each route still loads a the top of the page (0,0), rather than remembering my scroll position. Thoughts on what I'm missing?

Here's my router code:

const scrollBehavior = (to, from, savedPosition) => {
  if (savedPosition) {
    return savedPosition;
  } else {
    return { x: 0, y: 0 };
  }
};
const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
  scrollBehavior,
});
2 Answers

Have you checked for history.pushState support in the browser you are testing? Also, log the savedPosition because no scrolling will happen if the values are falsy. When creating the router instance, you can provide the scrollBehavior function as given,

const router = new VueRouter({
  routes: [...],
  scrollBehavior (to, from, savedPosition) {
      return { x: 0, y: 0 }
  }
})

The scrollBehavior function receives the to and from route objects. The third argument, savedPosition, is only available if this is a popstate navigation (triggered by the browser's back/forward buttons).

The function can return a scroll position object. The object could be in the form of:

{ x: number, y: number }
//or
{ selector: string, offset? : { x: number, y: number }} //offset only supported in 2.6.0+

If a falsy value or an empty object is returned, no scrolling will happen.

Note: this feature only works if the browser supports history.pushState

If you want, You can store the current scroll offset before navigating. Here is how you can do it.

const container = document.querySelector('.container')
let scrollOffset = {x: container.scrollTop, y: container.scrollLeft}

Now, store the scrollOffset before routing, when the savedPosition is falsy, You can use this object.

  scrollBehavior(to, from, savedPosition) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (to.hash) {
          return resolve({ selector: to.hash });
        } else if (savedPosition) {
          return resolve(savedPosition);
        } else {
          resolve(document.getElementById("app").scrollIntoView({ behavior: "smooth" }));
        }
      }, 1200);
    });
   
  },
Related