1

I am using Vue 3 and vue-router 4.

If I have a hash link in a 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>

And in my router I have

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

Clicking on the router links scrolls to the desired position, but during the scroll the component is re-created, so I lost all data previously fetched 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 runs again so the component is re-created. If I click on the same hash link, it only scrolls, the component stays alive. Clicking on any other hash link the component is re-created again.

rrd
  • 1,441
  • 2
  • 15
  • 36

1 Answers1

0

You could probably just use a normal link Tag for that case:

<a href="#l1">Section - 1</a>

If you want to use a <router-link>, read this issue (https://forum.vuejs.org/t/how-to-handle-anchors-bookmarks-with-vue-router/14563), where many suggestions are given on how to achieve the desired result.

floriankapaun
  • 472
  • 1
  • 4
  • 19
  • Using an `a` in a SPA context may cause quite some issues usually. And this can probably be achieved while keeping the usage of the vue router. – kissu Mar 15 '22 at 13:19
  • 1
    That's why I added a link to some ``-based solutions. But thanks for elaborating on why it's probably the better idea to use `` in this case. – floriankapaun Mar 15 '22 at 13:22
  • I'm saying that mainly because I saw a lot of people nuking their SPA with some `a` tags. Common mistake around here. Wasn't particularly blaming here. – kissu Mar 15 '22 at 13:27
  • Using the `a` tag results the same, the component is re-created. I have checked the forum topic, but it is a different problem and the solution does not work in this case. – rrd Mar 15 '22 at 13:33