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.