SoFunction
Updated on 2025-04-05

Detailed explanation of the role of keep-alive component in Vue

The role of keep-alive component is for your reference

effect:ForKeep component stateorAvoid re-rendering(The function of caching)

For example: When a directory page and a details page, users often: open the directory page => enter the details page => return to the directory page => open the details page, so the directory page is a page that is frequently used, so you can use the directory component.<keep-alive></keep-alive>Cache so that every time the user returns to the directory,Quick rendering from cache,andNo need to re-render

property

This tag has two attributes including and exclude:

  • include: string or regular expression. Only matching components will be cached
  • exclude: string or regular expression. No matching components are cached.

usage

&lt;!-- Basic --&gt;
&lt;keep-alive&gt;
 &lt;component :is="view"&gt;&lt;/component&gt;
&lt;/keep-alive&gt;

&lt;!-- Subcomponents for multiple conditional judgments --&gt;
&lt;keep-alive&gt;
 &lt;comp-a v-if="a &gt; 1"&gt;&lt;/comp-a&gt;
 &lt;comp-b v-else&gt;&lt;/comp-b&gt;
&lt;/keep-alive&gt;

&lt;!-- Common Applications --&gt;
&lt;keep-alive&gt;
 &lt;router-view&gt;&lt;/router-view&gt;
&lt;/keep-alive&gt;

Notice:It is used in one of itsDirect subcomponentsWhen switched, the situation is required to be simultaneouslyOnly oneThe child elements are rendered

Use of include and exclude attributes

The include and exclude properties allow components to be cached conditionally. Both can be divided into strings, regular expressions, or an array with commas.

&lt;!-- Comma-separated strings --&gt;
&lt;keep-alive include="a,b"&gt;
 &lt;component :is="view"&gt;&lt;/component&gt;
&lt;/keep-alive&gt;

&lt;!-- Regular expressions (use `v-bind`) --&gt;
&lt;keep-alive :include="/a|b/"&gt;
 &lt;component :is="view"&gt;&lt;/component&gt;
&lt;/keep-alive&gt;

&lt;!-- Array (use `v-bind`) --&gt;
&lt;keep-alive :include="['a', 'b']"&gt;
 &lt;component :is="view"&gt;&lt;/component&gt;
&lt;/keep-alive&gt;

Match first check the componentYour own name option, if the name option is not available,Match its local registration name

Life hook

  • keep-alive provides two life hooks, namelyactivatedanddeactivated. Because keep-alive will save the component in memory and will not be destroyed or recreated, the component's created and mounted functions will not be called again.
  • Components wrapped in keep-alive have two unique life cycles after being cached: activated and deactivated. activated lifecycle is called when component is activated, deactivated lifecycle is called when component is deactivated.

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.