SoFunction
Updated on 2025-04-03

vue2.0 keep-alive best practices

The best practices of keep-alive for your reference. The specific content is as follows

1. Basic usage

vue2.0 provides a keep-alive component to cache components, avoid loading corresponding components multiple times and reduce performance consumption

<keep-alive>
<component>
 <!-- Components will be cached -->
</component>
</keep-alive>

Sometimes it may be necessary to cache all pages of the entire site, and the request will usually be triggered as soon as the page enters.
When using keep-alive

<keep-alive><router-view></router-view></keep-alive>

Write the first trigger request in the created hook function to implement cache.
For example, the list page, I went to the details page. When I came back, I was still on the original page.

2. Cache some pages or components

(1) Use router. meta attribute

// This is the most commonly used method&lt;keep-alive&gt;
  &lt;router-view v-if="!$"&gt;&lt;/router-view&gt;
&lt;/keep-alive&gt;
&lt;router-view v-if="$"&gt;&lt;/router-view&gt;

router settings

... 
 routes: [
  { path: '/', redirect: '/index', component: Index, meta: { keepAlive: true }},
  {
   path: '/common',
   component: TestParent,
   children: [
    { path: '/test2', component: Test2, meta: { keepAlive: true } } 
   ]
  }
  ....
  // means both index and test2 use keep-alive

(2). Use the new attribute inlcude/exclude

After 2.1.0, two attributes include/exclude are provided, and corresponding components can be cached in a targeted manner.

&lt;!-- comma-delimited string --&gt;
&lt;keep-alive include="a,b"&gt;
 &lt;component :is="view"&gt;&lt;/component&gt;
&lt;/keep-alive&gt;
&lt;!-- regex (use v-bind) --&gt;
&lt;keep-alive :include="/a|b/"&gt;
 &lt;component :is="view"&gt;&lt;/component&gt;
&lt;/keep-alive&gt;

// where a and b are the name of the component

Note: This method is used to know the name of the component in advance.

(3) Dynamic judgment

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

Set includedComponents dynamically

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.