vue router scroll to hash without refreshing component
P粉322319601
P粉322319601 2024-03-26 09:37:39
0
1
433

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粉322319601
P粉322319601

reply all(1)
P粉092778585

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!