首页 > 解决方案 > 如何在 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

我该如何解决这个问题?

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

标签: nuxt.js

解决方案


First, you need to overwrite the router default behavior like this. Paste this anywhere inside your 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' })
        }
      }
    }

Then your anchor link should be like this:

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

推荐阅读