Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js scroll to top of new page route after setTimeout

I have a page transition that doesn't work nicely when the scroll to the top of a new route is instant. I'd like to wait 100ms before it automatically scrolls to the top. The following code doesn't end up scrolling at all. Is there a way to do this?

export default new Router({
    mode: 'history',
    routes: [
        {
            path: '/',
            name: 'Home',
            component: Home
        }
    ],
    scrollBehavior (to, from, savedPosition) {
        setTimeout(() => {
            return { x: 0, y: 0 }
        }, 100);
    }
})
like image 506
frosty Avatar asked Sep 06 '25 09:09

frosty


2 Answers

This is natively supported by Vue now, use scrollBehaviour, like this:

export default new Router({
  scrollBehavior() {
    return { x: 0, y: 0 };
  },
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    }
  ],
  mode: 'history'
});

More here.

like image 190
Edgar Quintero Avatar answered Sep 08 '25 10:09

Edgar Quintero


The other answers fail to handle edge cases such as:

  1. Saved Position - The saved position occurs when the user clicks the back or forward positions. We want to maintain the location the user was looking at.
  2. Hash Links - E.g. http://example.com/foo#bar should navigate to the element on the page with an id of bar.
  3. Finally, in all other cases we can navigate to the top of the page.

Here is the sample code that handles all of the above:

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
  scrollBehavior: (to, from, savedPosition) => {
    if (savedPosition) {
      return savedPosition;
    } else if (to.hash) {
      return {
        selector: to.hash
      };
    } else {
      return { x: 0, y: 0 };
    }
  }
});
like image 22
Muhammad Rehan Saeed Avatar answered Sep 08 '25 12:09

Muhammad Rehan Saeed