Page not scrolling to top when route changes in Nuxt JS

Viewed 2428

I'm trying to always go on the top of the page when route changes with Nuxt.

So I've put this into my app/router.scrollBehavior.js file:

export default function (to, from, savedPosition) {
  return { x: 0, y: 0 }
}

But it always returns to the last saved position (which is always null in my console by the way).

Any idea of what I could miss here?

4 Answers

For Nuxt v3.0.0-rc.3

Create file named route.global.ts on middleware/ folder

Then write this in file:

export default defineNuxtRouteMiddleware((to, from) => {
  if (to.path !== from.path && process.client) {
    window.scrollTo(0, 0)
  }
})

I use Nuxt 3 (npm:nuxt3@3.0.0-rc.4-27588443.cf25525), none of the solutions work for me. Finally this works:

/plugins/scrollToTop.js (any filename will work, just put it in the plugins folder)

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.$router.options.scrollBehavior = async (to, from, savedPosition) => {
    if (to.path !== from.path && process.client) {
      window.scrollTo(0, 0);
    }
  };
});

At the end, GSAP was conflicting with OP's scrolling behavior.
Removing it, solved all the issues related to Nuxt, nothing was actually wrong with the router.scrollBehavior.js file.

Related