【问题标题】:Problem with nuxt-links navigation to pages with hashes/anchorsnuxt-links 导航到带有哈希/锚的页面的问题
【发布时间】:2019-08-31 03:12:44
【问题描述】:

我在我的网站导航中使用 nuxt-links,其中大多数指向主页中的散列元素/锚点,例如:

<nuxt-link
  v-else
  class="text-link"
  :to="localePath('index') + #hash"
>

如果当前在主页上,但当我导航到其他站点时,它会完成它的工作,例如。 /about 并单击导航栏 nuxt 链接(所以我想从 /about 导航到 /#hash 或 /any-other-site#hash)我收到一个 nuxt 错误,以检查显示“无法读取”的控制台属性 'offsetTop' 为 null"。

我在 nuxt.config 中的路由器配置(没有它,我什至无法滚动到与该元素位于同一站点的锚定元素!):

  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' });
      }
  },

在 :to 属性中,我尝试了 'hash' '#hash',但没有任何效果。请有人帮我解决这个问题吗?如何导航到不同的页面 + #anchor(以便滚动到该锚点?)

【问题讨论】:

  • 如果您使用的是 nuxt 2.4+ 版本,那么 this 是您应该设置滚动行为的方式,特别是底部的 return Promise 部分。
  • @Andrew1325 使用默认配置(您提到的那个),当我单击 mu nuxt 链接 &lt;nuxt-link to="/#hash"&gt; 时,滚动到该元素永远不会发生。点击不会触发任何事情。

标签: javascript vue.js vue-router nuxt.js


【解决方案1】:

有点晚了,但这是我能够实现的。感谢 Sivuyile-TG-Magutywa

 <nuxt-link :to="{ path: localePath('index'),hash:'#about'}">
          {{ $t("menu.about") }}
 </nuxt-link>

输出

https://www.shrek.com/fr/about

【讨论】:

    【解决方案2】:

    使用这种方式,与 getBoundingClientRect().top+window.scrollY,在小节的情况下对我来说效果更好:

    if (to.hash) {
            let el = await findEl(to.hash)
            if ('scrollBehavior' in document.documentElement.style) {
              return window.scrollTo({ top: el.getBoundingClientRect().top+window.scrollY, behavior: 'smooth' })
            } else {
              return window.scrollTo(0, el.getBoundingClientRect().top+window.scrollY)
            }
          }
    
    

    【讨论】:

    • 救命稻草!传奇!
    【解决方案3】:

    如果您使用Nuxt-Link,这里遇到此问题的任何人都是一个简单的解决方案

    而不是使用 &lt;nuxt-link to="#contact" &gt;Contact&lt;/nuxt-link&gt; 这不起作用。 使用&lt;nuxt-link :to="{ path: '/',hash:'#contact'}"&gt;Contact&lt;/nuxt-link&gt;

    path 是您将导航到的页面

    hash 是您将滚动到的位置

    希望这对某人有所帮助。

    【讨论】:

    • 刚刚在 Nuxt 的 ^2.0.0 版本中进行了测试,但这似乎不起作用。
    • 在同一版本@FooBar 上为我工作,尽管它不会滚动到 div,它只是直接转到哈希。我没有弄乱默认的路由器滚动行为。
    猜你喜欢
    • 2021-12-17
    • 2017-02-02
    • 2013-12-25
    • 2014-09-10
    • 2020-04-05
    • 2015-06-02
    • 1970-01-01
    • 2011-06-27
    • 2019-07-31
    相关资源
    最近更新 更多