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

frosty picture frosty · Mar 1, 2017 · Viewed 23.5k times · Source

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);
    }
})

Answer

Edgar Quintero picture Edgar Quintero · Jun 18, 2018

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.