English | 中文
Stack-Keep-Alive
is an automatic management tool for page cache in Vue.js
(Vue 3.x) project.
Online Demo, Check the Vue-devtools Panel
The built-in keep-alive
component is very useful in development, but it is not intelligent enough, it is difficult to clean up the page cache later, you need to use exclude
and include
API to save memory, and it cannot be accurately destroyed for different pages created by the same component.
If you have experienced mobile native development, you will not be troubled by this problem, because the model similar to NavigationController to manage each page is a stack structure, and the top page of the stack is destroyed when returning back.(The API is push
and pop
)
- Automatically detect forward or backward
- Automatically destroy the current page cache when routing back
- Automatically create a new cache instance when routing forward, regardless of whether the component is cached or not
- After refreshing the page, it is still able to accurately identify forward or backward
replaceStay
whitelist helps cache pages when tab switchingsingleton
allows you to set a globally unique page instancesk-transition
allows you to use two animations to simulate the native stacking effect
npm i -s stack-keep-alive
|yarn add stack-keep-alive
- Replace the
keep-alive
component withstack-keep-alive
(no need to import, registered global component)
<router-view v-slot="{ Component }">
<stack-keep-alive v-slot='{ key }'>
<component :is="Component" :key='key'/>
</stack-keep-alive>
</router-view>
- When the app is initialized, use the StackKeepAlive plugin
import StackKeepAlive from 'stack-keep-alive'
const app = Vue.createApp({})
app.use(StackKeepAlive)
...
When the tab bar is switched, some tab pages need to be retained, and these paths can be configured in replaceStay
<stack-keep-alive v-slot='{ key }' :replaceStay='["/foo"]'>
<component :is="Component" :key='key'/>
</stack-keep-alive>
For use with transition, you need to replace the transition component with the built-in sk-transition component.Use name
and back_name
to achieve two different animation effects. Sameple Code here
<router-view v-slot="{ Component }">
<sk-transition name='slide-left' back_name='slide-right'>
<stack-keep-alive v-slot="{ key }">
<component :is="Component" :key='key'/>
</stack-keep-alive>
</sk-transition>
</router-view>
Sometimes it is expected that a component is only created once in the entire application life cycle, such as the common shopping cart page, in this case, use singleton
to configure singleton route
<stack-keep-alive v-slot='{ key }' :singleton='["/foo"]'>
<component :is="Component" :key='key'/>
</stack-keep-alive>