Vue.js, how to scroll to an anchor via ID without navigating to a route

Viewed 486

I have Vue + vue-router for navigation through pages in an app, but I also need to the ability to move to an ID/Anchor without routing. Currently, router always activates and changes the URL to a new page with the name of the ID instead of moving to the ID on the same page.

<a href="#example">link</a>

The route set-up:

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior (to) {
    if (to.hash) {
      return {
        selector: to.hash
      }
    }
  }
})

When clicking the link, the page scrolls to the ID, but then routes away to a non-existent page http://localhost:8080/#/example.

I'm really not sure how to use the anchor/ID without it being hijacked by vue-router.

1 Answers

if you are on the same page you can create a method and use window.scrollTo.

here it's an example function:

scrollToContent() {
      window.scrollTo(
        0,
        document.getElementById("content").getBoundingClientRect().y +
          window.scrollY -
          120
      );
    },
Related