SoFunction
Updated on 2025-04-12

Summary of several implementation methods of vue routing cache

This article describes several implementation methods of vue routing cache. Share it for your reference, as follows:

In our daily development, we sometimes encounter page cache, especially e-commerce projects, and some states of the product list need to be cached.

Here are a brief introduction to several ways of vue routing caching.

1. All caches

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

Use directlykeep-alive Tag parcelrouter-view Tags can cache all pages

2. Cache a single specified route

&lt;keep-alive include="The name of the route"&gt;
  &lt;router-view&gt;&lt;/router-view&gt;
&lt;/keep-alive&gt;

Use directly keep-alive Tag parcelrouter-view Tags, then useinclude Specify the page to which it needs to be cachedname name

Available v-bind Bind onename Arrays can also be separated by ',', regular expressions can also be used. It is recommended to use the third type in case of multiple cases.

Note: It is the name of the cache page, not the name of the cache page route

3. Cache multiple specified routes

<keep-alive>
  <router-view v-if="$"></router-view>
</keep-alive>
<router-view v-if="!$"></router-view>

Use tworouter-view Tags are used as cached and uncached route exits respectively. When routing configuration, you only need to add the page to be cached.meta Properties, then addkeepAlive The property is set totrue Just do it. For example:

{
 path:'/test',
 name:'Test',
 component: Test,
 meta: {keepAlive: true} //true cache false does not cache}

IV. activated and deactivated

activateddeactivated These two lifecycle functions must be usedkeep-alive It will only exist after the component, otherwise it will not exist.

When introducedkeep-alive When the page entered for the first time

The trigger order of the hook created-> mounted -> activated, triggered when exiting.

When entering again (forward or backward), only activated is triggered

Note: Keep-alive is followed by the package router-view component, and no other tags appear, otherwise the page will not be cached.

If you need to refresh the page without a white screen while the route remains unchanged, please refer to the previous article:The route remains unchanged, and the page is refreshed without a white screen

I hope this article will be helpful to everyone's programming.