0

I'm using a <nuxt-link> component in my Nuxt application and I have the following problem:

  • 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.

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 ? (Without refreshing the page)

Here is what my nuxt-link looks like

<nuxt-link :to="{ path: localePath('/'), hash: '#homepage' }"
>
  <span>Homepage</span>
</nuxt-link>
Théo Lavaux
  • 1,364
  • 3
  • 22
  • 46

2 Answers2

2

I believe that you should be able to add a click handler to your 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)

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

Merc
  • 4,241
  • 8
  • 52
  • 81
1

Got it to work with this function bound to a click.native event as suggested by @Merc.

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
        })
      }
    }
  }
Théo Lavaux
  • 1,364
  • 3
  • 22
  • 46