如何在 nuxt.js 和 bootstrap 站点中平滑滚动?

tol*_*yan 4 nuxt.js

我尝试使用 nuxt.js 和这个模板制作网站。我将文件夹:css、img、js、scss、vendor 从模板复制到我的 nuxt 项目的静态文件夹。在此之后,我制作了nuxt.config.jspages/index.vue文件。除了页面上的平滑滚动外,所有工作都很好。我在浏览器控制台中看到错误:

agency.min.js:7 Uncaught TypeError: Cannot read property 'top' of undefined
at a (agency.min.js:7)
at agency.min.js:7
at agency.min.js:7
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

UPD:您可以下载此项目以重现错误

小智 14

首先,您需要像这样覆盖路由器的默认行为。将此粘贴到您的 nuxt.config.js 中的任何位置:

   {
     //.......
      router: {
        scrollBehavior(to) {
          if (to.hash) {
            return window.scrollTo({
              top: document.querySelector(to.hash).offsetTop + window.innerHeight,
              behavior: 'smooth'
            })
          }
          return window.scrollTo({ top: 0, behavior: 'smooth' })
        }
      }
    }
Run Code Online (Sandbox Code Playgroud)

那么你的锚链接应该是这样的:

<nuxt-link :to="{ path: '/',hash:'#about'}">Contact</nuxt-link>
Run Code Online (Sandbox Code Playgroud)

  • 我不知道为什么没有人赞成这个答案。这是我使用 Nuxt 实现平滑滚动的唯一方法。请务必在 css 中关闭“html {scrolling: smooth}”。 (3认同)

Riz*_*han 6

Sajjad Aljileezi 的回答是有效的,但是,如果您正在寻找更简单的替代方法,那就是在自定义 CSS 文件中添加这个简单的行。您可以将所述文件导入到您的nuxt.config.js文件中。

html {
   scroll-behavior: smooth;
}
Run Code Online (Sandbox Code Playgroud)

nuxt.config.js文件可能是这样的:

css: ['~/assets/style/yourcssfile.css']
Run Code Online (Sandbox Code Playgroud)


小智 0

这是由于服务器端渲染,您正在使用 SSR 无法解析的内容,可能是对窗口或文档的调用。

如果需要指定仅在客户端导入资源,则需要使用process.client变量。

您可以在这里查看: https: //nuxtjs.org/faq/window-document-undefined