![](/img/trans.png)
[英]How to destroy a VueJS component that is being cached by <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 並且想要這種行為,這樣組件就不會再次掛載,它會再次執行對服務器的異步調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.