nuxt-link: 重定向到具有散列的同一个锚点

nuxt-link: redirect to the same anchor with hash

我在我的 Nuxt 应用程序中使用 <nuxt-link> 组件,但遇到以下问题:

我如何才能覆盖此行为,以便当我单击 nuxt-link 时,无论我之前单击过什么,它都会滚动到所需的部分? (不刷新页面)

这是我的 nuxt-link 的样子

<nuxt-link :to="{ path: localePath('/'), hash: '#homepage' }"
>
  <span>Homepage</span>
</nuxt-link>

我相信您应该能够将点击处理程序添加到您的 nuxt-link。

<nuxt-link
  :to="{ path: localePath('/'), hash: '#homepage' }"
  @click.native="scroll"
>
  Homepage
</nuxt-link>

(不确定 @click.native,如果不行就试试 @click

然后在您的方法中:

methods: {
    scroll() {
      // your scroll function, probably reading document.documentElement.scrollTop or similar
    // if necessary check this.$route if the hash is already present, if so only do it in that case...
    },
}

希望这能给你一个起点?! 干杯

按照@Merc 的建议,将其与绑定到 click.native 事件的函数一起使用。

handleScroll(anchorId: string): void {
    if (this.$route.hash) {
      const anchor = document.querySelector(`#${anchorId}`)

      // Check if the anchor has been found
      if (anchor) {
        window.scrollTo({
          // Scroll so that the anchor is at the top of the view
          top: anchor.getBoundingClientRect().top + window.pageYOffset
        })
      }
    }
  }