Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scroll behaviour not working in Nuxt3 Application

I am facing issue with scroll behavior in my Nuxt3 project when using nuxt-link.

The problem is that if I visit any page from my current page using <nuxt-link>, that page scroll position is similar to what I had in previous page.

But I expect that page scroll position to reset to top when I change pages.

I followed some answers by @kissu at https://stackoverflow.com/a/68819388/17473694 but none of them seems to be working.

currently I have

/plugins/route.scrollbehaviour.js

import { defineNuxtPlugin } from '#app'
export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.$router.options.scrollBehavior = (to, from, savedPosition) => {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

My Package.json ( for any conflict )

{
  "devDependencies": {
    "@nuxtjs/tailwindcss": "^5.3.0",
    "nuxt": "3.0.0-rc.6",
    "nuxt-lodash": "^2.2.0",
    "nuxt-schema-org": "^0.6.2",
    "unplugin-vue-components": "^0.21.1"
  },
  "dependencies": {
    "@ant-design/icons-vue": "^6.1.0",
    "@mdi/js": "^6.7.96",
    "@nuxtjs/device": "Redemption198/device-module",
    "@pinia/nuxt": "^0.3.0",
    "@tailwindcss/typography": "^0.5.2",
    "ant-design-vue": "^3.2.10",
    "date-fns": "^2.28.0",
    "mdi-vue": "^3.0.13",
    "pinia": "^2.0.16",
    "primeicons": "^5.0.0",
    "primevue": "^3.15.0",
    "vant": "^3.5.2",
    "vue-uuid": "^3.0.0",
    "vue3-carousel": "^0.1.40",
    "vue3-google-login": "^2.0.11"
  }
}

after removing every UI package when it wasn't working, now i find whats causing this error. I have added following CSS in layouts/default.vue. if i remove this css then things works fine. but i added this to hide extra horizontal white space in mobile view.

<style>
html, body {
  max-width: 100%;
  overflow-x: hidden;
}
</style>

this fixes problem somehow.

<style>
html, body {
  max-width: 100%;
  overflow-x: clip;
}
</style>
like image 978
imthegrv Avatar asked Sep 18 '25 19:09

imthegrv


1 Answers

Based on Nuxt3's docs

You can tap into the RouterConfig in the /app/router.options.ts file.

import type { RouterConfig } from "@nuxt/schema";

export default <RouterConfig>{
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition;
        } else {
            return {
                top: 0
            };
        }
    }
};
like image 160
Jonathan Knoll Avatar answered Sep 21 '25 07:09

Jonathan Knoll