簡體   English   中英

從 keep-alive 中手動移除(並銷毀)組件

[英]Manually remove (and destroy) a component from keep-alive

我找不到如何訪問從 Vue Route 加載並通過<keep-alive><component>持久化的組件實例,以便我可以以編程方式卸載它。

我正在實現一個動態選項卡系統,以便每個選項卡呈現一個 URL,然后顯示其聲明的組件。 我不想在每次創建新選項卡或 select 另一個選項卡時加載新路由時卸載組件。 我通過在一個名為 MultiTabs 的自定義組件中結合keep-alive/component來實現它:

<multi-tabs>
   <router-view v-slot="{ Component }">
       <keep-alive>
           <component :is="Component" />
       </keep-alive>
   </router-view>
</multi-tabs>

到目前為止,一切都很好。 假設我有這些路線:

//...
{
   path: '/foo',
   name: 'Foo',
   component: () => import("./components/pages/Foo.vue"),
},
{
   path: '/bar',
   name: 'Bar',
   component: () => import("./components/pages/Bar.vue"),
},
//...

router.beforeEach((to, from, next) => {
   store.dispatch('addTab', to); // --> Vuex would then add this route to a list of tabs (routes), which I will retrieve from the MultiTabs component.
   next();
});

從我的 MultiTabs 組件中,我獲取所有選項卡(查詢路由),並將它們顯示為選項卡導航,以及應該呈現的組件:

MultiTabs.vue:

<template>
   <!-- ... -->
   <!-- MultiTab has a close button which emits the tabClosed event  -->
   <multi-tab 
      v-for="route of storedTabs" 
      :key="route.fullPath" 
      :route="route" 
      @selectedRoute="selectRoute" 
      @tabClosed="closeTab"
      >
   </multi-tab>
   <!-- ... -->
   <!-- This is where the component for the selected route is rendered -->
   <div class="tab-pane">
      <slot/>
   </div>
</template>

因此,當用戶單擊選項卡中的關閉按鈕時,我想從 memory 中釋放相應的組件。 請注意,導航選項卡不會發生這種情況,因為我使用了 keep-alive 並且想要這種行為,這樣組件就不會再次掛載,它會再次執行對服務器的異步調用。

不幸的是,這樣的功能還不存在。 Vue repo 中幾乎沒有問題,包括這個問題,您可以在其中找到一個 hacky 示例如何做到這一點,但它使用了一些內部細節,因此使用它可能會有風險,因為這些細節可以隨時更改......

這是一個正在進行的討論/RFC ,所以如果你需要這個,請隨時參與討論或投票

在實現上述功能之前,您最好的選擇可能是重構您的組件並執行您需要做的事情,不僅是在created / mounted的鈎子中,而且在激活的鈎子中,當保持活動組件被激活時調用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM