Home  >  Q&A  >  body text

vue router scroll to hash without refreshing component

I'm using Vue 3 and vue-router 4.

If I have a hash link in the component

<router-link :to="{ hash: '#l1' }">Section - 1</router-link>
<router-link :to="{ hash: '#l2' }">Section - 2</router-link>
...
<section id="l1">...</section>
<section id="l2">...</section>

In my router I have

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (to.hash) {
      return {
        el: to.hash,
      }
    }
  },
})

Clicking the router link scrolls to the desired location, but the component is recreated during the scroll, so I lose all the data I had previously obtained from the API.

Is there a way to avoid component re-creation if the navigation is within the same page?

UPDATE If I click on any of this hash links, the component's setup method is run again so that the component is recreated. If I click on the same hash link it just scrolls and the component remains active. Click any other hash link and the component will be recreated again.

P粉322319601P粉322319601207 days ago440

reply all(1)I'll reply

  • P粉092778585

    P粉0927785852024-03-27 00:12:02

    For this case you might just use a normal link tag:

    Section - 1

    If you want to use <router-link>, please read this question (https://forum.vuejs.org/t/how-to-handle-anchors-bookmarks- with-vue-router/14563), many of which give suggestions on how to achieve the desired results.

    reply
    0
  • Cancelreply