【问题标题】:How make smooth scrolling in nuxt.js and bootstrap site?如何在 nuxt.js 和引导站点中平滑滚动?
【发布时间】:2018-12-17 09:35:42
【问题描述】:

我尝试使用 nuxt.js 和 this template 创建网站。我将文件夹:css、img、js、scss、vendor 从模板复制到我的 nuxt 项目的 static 文件夹。在此之后,我制作了 nuxt.config.js 和 pages/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

我该如何解决这个问题?

UPD:你可以download这个项目重现错误

【问题讨论】:

    标签: nuxt.js


    【解决方案1】:

    首先,您需要像这样覆盖路由器的默认行为。将此粘贴到 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' })
            }
          }
        }
    

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

    <nuxt-link :to="{ path: '/',hash:'#about'}">Contact</nuxt-link>
    

    【讨论】:

    • 我不知道为什么没有人赞成这个答案。这是我可以使用 Nuxt 平滑滚动的唯一方法。请务必在您的 CSS 中关闭 html {scrolling: smooth}。
    • 它确实有效,而且是最有效的方式,您无需安装任何可以增加千字节的软件包
    • 为了不弄乱nuxt.config 是否可以将此代码移动到插件文件中?
    【解决方案2】:

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

    html {
       scroll-behavior: smooth;
    }
    

    nuxt.config.js 文件应该是这样的:

    css: ['~/assets/style/yourcssfile.css']
    

    【讨论】:

      【解决方案3】:

      从 Nuxt v2.9.0 开始,您可以使用文件来覆盖路由器的滚动行为。此文件应放在 ~/app/router.scrollBehavior.js 中(注意:如果在 Windows 上运行,文件名区分大小写)。

      资源:

      这是一个平滑滚动到哈希链接的示例,否则滚动到顶部。

      export default function (to, from, savedPosition) {
        if (to.hash) {
          return {
            selector: to.hash,
            behavior: 'smooth'
          }
        } else {
          return { x: 0, y: 0, behavior: 'smooth' }
        }
      }
      

      【讨论】:

        【解决方案4】:

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

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

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

        【讨论】:

          【解决方案5】:

          似乎在 nuxt 2.16+ 中用于平滑滚动的基本设置

          <button @click=scrollToTop()>Jump to top of page</button>
          

          。 . .

          methods: {
              scrollToTop() {
                window.scrollTo({ top: 0 });
              }
            }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-04-17
            • 2020-04-26
            • 1970-01-01
            • 1970-01-01
            • 2018-10-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多