Home » vue » Internal links in Vue.js: Using the vue-router to jump to a specific section in a view with an id

Internal links in Vue.js: Using the vue-router to jump to a specific section in a view with an id

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have a Home view and a Blog view.
Trying to use a <router-link> to jump from the Home view to a specific section in the Blog view.
The section looks like <section id="fundamentals" class="section">

In html I believe it would work like <a href="/blog/#fundamentals">Jump to specific blog section</a>
How can I replicate this using the vue-router?

Answers:

Check out the docs for scroll behavior. In particular, the discussion of scrolling to a hash:

If you want to simulate the "scroll to anchor" behavior:

scrollBehavior (to, from, savedPosition) {
  if (to.hash) {
    return {
      selector: to.hash
      // , offset: { x: 0, y: 10 }
    }
  }
}

###

You could use this and use the @click.native property of the router as specified on the top answer. You could also use the vue-scrollto plugin which is much easier. It’s as easy as

<a href="#" v-scroll-to="'#element'">Scroll to #element</a>
 
<div id="element">
    Hi. I'm #element.
</div>

after you setup the plugin.