首頁  >  問答  >  主體

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 天前442

全部回覆(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
  • 取消回覆