简体   繁体   English

nuxt-link:使用哈希重定向到同一个锚点

[英]nuxt-link: redirect to the same anchor with hash

I'm using a <nuxt-link> component in my Nuxt application and I have the following problem:我在 Nuxt 应用程序中使用了<nuxt-link>组件,但遇到以下问题:

  • When I click for the first time on the link, everything works fine, if needed the page is changed and the anchor works perfectly当我第一次点击链接时,一切正常,如果需要,页面会更改并且锚点工作正常
  • However, if I scroll a bit on the page, and click the link again, nothing happens, because the url is already present in the browser navbar I assume.但是,如果我在页面上滚动一点,然后再次单击该链接,则不会发生任何事情,因为我假设该 url 已经存在于浏览器导航栏中。

How could I overwrite this behavior so that when I click on the nuxt-link , it scrolls to the desired section regardless of what I have clicked before ?我怎么能覆盖这种行为,以便当我点击nuxt-link ,无论我之前点击了什么,它都会滚动到所需的部分? (Without refreshing the page) (不刷新页面)

Here is what my nuxt-link looks like这是我的nuxt-link样子

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

I believe that you should be able to add a click handler to your nuxt-link.我相信您应该能够向您的 nuxt-link 添加点击处理程序。

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

(not sure about the @click.native , if that does not work just try @click ) (不确定@click.native ,如果这不起作用,请尝试@click

And then within your methods:然后在你的方法中:

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...
    },
}

Hope that gives you a point to start?!希望这能给你一个起点?! Cheers干杯

Got it to work with this function bound to a click.native event as suggested by @Merc.按照click.native建议,让它与绑定到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
        })
      }
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM