Skip to content

Vue-router, transitions and scrollBehavior - Page jumping back to top or changing scroll locationΒ #1466

@realcarbonneau

Description

@realcarbonneau

There is currently a problem with the vue-router and vue-transitions (outside of Quasar) that causes pages to jump back to the top before transitions and also to change scroll location when doing popstate navigations (browser back and forward buttons. Here are some details, please post comments or questions on this topic here.

vue-router with scrollBehavior currently works when there are NO transitions. The users scroll position will be retained between popstate navigations.

export default new VueRouter({
  // mode: 'history',
  routes,
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      // Keep scroll position when using browser buttons
      return savedPosition
    }
    else {
      return { x: 0, y: 0 }
    }
  }
})

Additionally, to ensure that the component state is retained (eg form field data, opened tabs, etc.) the keep-alive must be used

      <keep-alive>
        <router-view></router-view>
      </keep-alive>

For transitions on routes, there is a new Async scrollBehavior, but there are still some issues that are currently being worked on by the vue team. Here is the current partial solution. Note that the scrollBehavior delay is 1 second and the transition is 0.5s to emphasize the mechanics in play here.

export default new VueRouter({
  // mode: 'history',
  routes,
  scrollBehavior (to, from, savedPosition) {
    let position = { x: 0, y: 0 }
    // Keep scroll position when using browser buttons
    if (savedPosition) {
      position = savedPosition
    }

    // Workaround for transitions scrolling to the top of the page
    // However, there are still some problems being fixed by the vue team
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(position)
      }, 1000)
    })
  }
})

References:
https://router.vuejs.org/en/advanced/scroll-behavior.html

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions