Vue2/Router3 — scrollBehavior not working

Viewed 146

I'm trying to remember scroll position between routing pushes, NOT browser back/fwd navigation.

Case: on a long page of products, scrolling down and clicking on one of the items to see its details, then clicking a "back to list" button with a router push and (in my dreams) returning to where I was scrolled to on the product page.

This is my router. All the docs just give this basic config, but it doesn't work for me and I'm not sure if I need to add other logic in other components. Do I need to to save a 'savedPosition' in the state then get and set it in the router?

I'm also using beforeEach navigation guards but there isn't any scroll logic in there.

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