Solve the keep-alive page cache problem when vue-router
When wrapping dynamic components with keep-alive , inactive component instances are cached instead of being destroyed. keep-alive is an abstract component: it does not render a DOM element itself, nor does it appear in the chain of parent components. When a component is switched within keep-alive, its activated and deactivated lifecycle hook functions will be executed accordingly.
Function: Keep the state in memory during component switching, prevent repeated rendering of DOM, reduce loading time and performance consumption, and improve user experience.
Principle: When the created function is called, save the VNode node that needs to be cached in this.cache; when rendering (page rendering), if the name of the VNode meets the cache conditions (can be controlled by include and exclude), it will be from this.cache Take out the previously cached VNode instance for rendering.
In our daily development, we sometimes encounter page caching, especially for e-commerce projects, where some states in the product list must be cached.
The following is a brief introduction to several ways of vue route caching.
cache all
keep-alive
Wrap the tag directly with router-view
the tag to cache all the pages
<keep-alive>
<router-view></router-view>
</keep-alive>
Cache a single specified route
Also directly wrap keep-alive
the tag with the tag router-view
, and then use include
the name of the page that needs to be cached .
You can use v-bind
to bind a name array, or you can use ',' to separate it, or you can use regular expressions. In multiple cases, it is recommended to use the third one
注意:是缓存页面的 name 名称,而不是缓存页面路由的 name 名称
<keep-alive include="该路由的name名称">
<router-view></router-view>
</keep-alive>
<!-- 逗号分隔字符串 -->
<keep-alive include="a,b">
<component :is="view"></component>
</keep-alive>
Cache multiple specified routes
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
Use two router-view
tags as route exits for caching and non-caching respectively. When configuring the route, you only need to add meta
attributes to the page to be cached, and then keepAlive
set the added attribute to true. For example:
{
path:'/test',
name:'Test',
component: Test,
meta: {
keepAlive: true} //true缓存 false不缓存
}
activated和deactivated
activated
, deactivated
these two life cycle functions must be keep-alive
available after the component is used, otherwise they do not exist.
When introduced keep-alive
, the page first enters
the trigger sequence of hooks created-> mounted -> activated
, and fires when it exits deactivated
.
When re-entering (forward or backward), only triggeractivated
注意:keep-alive里面紧跟包裹 router-view 组件,而不能出现其他标签,不然会导致无法缓存页面。