Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js - Destroy a cached component from keep alive

Tags:

vue.js

My Vue app has a dynamic tabs mechanism.

Users can create as many tabs as the want on the fly, each tab having its own state (eg "Pages").

I am using the <keep-alive> component to cache the different pages.

<keep-alive include="page">
  <router-view :key="$route.params.id" />
</keep-alive>

But users can also "close" individual tab. As pages tend to store a lot of datas, I would like to delete the according page component from the cache, as the user close the tab.

How can I programmatically destroy a cached component inside keep-alive ?

like image 746
Thomas Avatar asked May 03 '19 06:05

Thomas


2 Answers

If you don't mind losing the state when a tab is added/removed, then you can try these:

  • Use v-if and turn off the keep-alive component and turn it back on in nextTick
  • Use v-bind on the include list, and remove "page" and add it back in nextTick
like image 57
Teddy Avatar answered Sep 22 '22 16:09

Teddy


<keep-alive :include="cachedViews">
  <router-view :key="key" />
</keep-alive>

cachedViews is the array of the route component name

First when create a tab, cachedViews push the cached route name, when you switch the opened tab, the current route is cached.

Second when close the tab, cachedViews pop the cached route name, the route component will destroyed.

like image 25
feasin Avatar answered Sep 18 '22 16:09

feasin