滚动行为在 Nuxt3 应用程序中不起作用

imt*_*grv 2 vue-router nuxt.js nuxtjs3

当我使用 Nuxt3 项目时,我遇到了滚动行为问题nuxt-link

问题是,如果我使用当前页面访问任何页面<nuxt-link>,该页面滚动位置与我在上一页中的位置类似。

但我希望当我更改页面时,页面滚动位置会重置到顶部。

我在/sf/answers/4817357191/上关注了 @kissu 的一些答案,但它们似乎都不起作用。

目前我有

/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 }
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

我的 Package.json (对于任何冲突)

{
  "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"
  }
}
Run Code Online (Sandbox Code Playgroud)

在删除所有不工作的 UI 包后,现在我找到了导致此错误的原因。我在layout/default.vue中添加了以下CSS。如果我删除这个 css 那么一切都会正常。但我添加它是为了隐藏移动视图中额外的水平空白。

<style>
html, body {
  max-width: 100%;
  overflow-x: hidden;
}
</style>
Run Code Online (Sandbox Code Playgroud)

这以某种方式解决了问题。

<style>
html, body {
  max-width: 100%;
  overflow-x: clip;
}
</style>
Run Code Online (Sandbox Code Playgroud)

tub*_*trr 7

基于 Nuxt3 的文档

您可以利用/app/router.options.ts文件中的 RouterConfig。

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

export default <RouterConfig>{
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition;
        } else {
            return {
                top: 0
            };
        }
    }
};
Run Code Online (Sandbox Code Playgroud)