首页  >  问答  >  正文

vue 路由器滚动到哈希而不刷新组件

我正在使用 Vue 3 和 vue-router 4。

如果我在组件中有一个哈希链接

<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>

在我的路由器中我有

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

单击路由器链接会滚动到所需位置,但在滚动期间会重新创建组件,因此我丢失了之前从 API 获取的所有数据。

如果导航位于同一页面内,是否有办法避免组件重新创建?

更新 如果我单击任何此哈希链接,组件的设置方法将再次运行,以便重新创建组件。如果我单击相同的哈希链接,它只会滚动,组件保持活动状态。 单击任何其他哈希链接,组件将再次重新创建。

P粉322319601P粉322319601207 天前436

全部回复(1)我来回复

  • P粉092778585

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

    对于这种情况,您可能只使用普通的链接标签:

    Section - 1

    如果您想使用 <router-link>,请阅读 这个问题 (https://forum.vuejs.org/t/how-to-handle-anchors-bookmarks-with-vue-router/14563),其中很多给出了如何达到预期结果的建议。

    回复
    0
  • 取消回复