Static GitHub Issues

[1036] scrollBehavior: Fires too early

prev: Problem with Session and Window
next: Confused on build

I'm relatively new to the Vue ecosystem (I have much ❤️ growing for it!), and I am having an issue with the vue-router scrollBehavior. I do not know if this is related to Nuxt, or if it's a vue-router issue.

Issue

scrollBehavior fires before route changes causing a very janky routing experience

Solution

Right now I am using this in my scrollBehavior:

    router: {
        scrollBehavior: function (to, from, savedPosition) {
            if (savedPosition) return savedPosition
            return false
        }
    },

For the pages that I need a scroll to top behavior, I am doing this in my page components:

mounted () {
    window.scrollTo(0, 0)
}

This is not giving me an ideal experience. I would still like to use a savedPosition for some pages, but I am using the mounted call to window to get around the jank and so those pages do not "use" the savedPosition as the scrollTo gets called after the component is mounted.

Setup

Default Nuxt scrollBehavior, at the time of this writing, the docs show this:

const scrollBehavior = (to, from, savedPosition) => {
  // savedPosition is only available for popstate navigations.
  if (savedPosition) {
    return savedPosition
  } else {
    let position = {}
    // if no children detected
    if (to.matched.length < 2) {
      // scroll to the top of the page
      position = { x: 0, y: 0 }
    }
    else if (to.matched.some((r) => r.components.default.options.scrollToTop)) {
      // if one of the children has scrollToTop option set to true
      position = { x: 0, y: 0 }
    }
    // if link has anchor,  scroll to anchor by returning the selector
    if (to.hash) {
      position = { selector: to.hash }
    }
    return position
  }
}

Expected

When I use a <nuxt-link> I should be routed to the new route, and for the cases when I should scroll to the top I should see the top of the next route. AKA: The scrollBehavior should fire "between" routes or "after I have left a route, and before I have entered a new one".

Actual

When I use a <nuxt-link> for the cases when I should scroll to the top, I first see a scroll to top behavior of the route that I am currently on (so it flashes to the top of the page if I am scrolled down), and then I am routed to my new route.

TODO

  • Include a repo soon, if necessary, for reproducing the issue.
  • Update solution section with a better solution than what I currently have
<!--cmty--><!--cmty_prevent_hook--><div align="right"><sub><em>This question is available on <a href="https://nuxtjs.cmty.io">Nuxt.js</a> community (<a href="https://nuxtjs.cmty.io/nuxt/nuxt.js/issues/c899">#c899</a>)</em></sub></div>