Detailed explanation of vue3 cache page keep-alive and unified routing processing

Detailed explanation of vue3 cache page keep-alive and unified routing processing

1. Introduction

When using routing to jump to other pages, it is required to cache the current page. For example, when jumping from a list page to a detail page, the list content needs to be cached and the scroll bar position needs to be saved. Sometimes, some content in the page that needs to be cached is not cached. In short, there are various situations. Here are some examples.

The usage of vue2 and vue3 is different

The created() method and mounted() method are executed when the page is initialized. If the page is cached, these two methods will not be executed. Also, if the page is cached, the destroyed() method in vue2 and the unmounted() method in vue3 will not be executed.

The activated() method is executed every time you enter the page

2. Use

1. Differences between vue2 and vue3

vue2:

<template>
	<div id="nav">
	    <router-link to="/">Home</router-link> |
	    <router-link to="/about">About</router-link>
  	</div>
	<!-- vue2.x configuration -->
   <keep-alive>
    <router-view v-if="$route.meta.keepAlive" />
  </keep-alive>
  <router-view v-if="!$route.meta.keepAlive"/>
</template>

vue3:

<template>
	<div id="nav">
	    <router-link to="/">Home</router-link> |
	    <router-link to="/about">About</router-link>
  	</div>
  <!-- Vue3.0 configuration Component is fixed writing -->
  <router-view v-slot="{ Component }">
    <keep-alive>
      <component :is="Component" v-if="$route.meta.keepAlive"/>
    </keep-alive>
    <component :is="Component" v-if="!$route.meta.keepAlive"/>
  </router-view> 
</template>

Configuration in route.js:

path: '/',
name: 'Home',
component: Home,
meta:{
  keepAlive: true
}

Effect:

2. Some data on the page does not need to be cached

You can handle the logic that requires partial refresh in the activated() method

...
Data that needs to be partially refreshed: <input type="text" v-model="newStr" />
...
data() {
  return {
    newStr: "2",
  };
},
mounted() {
  console.log("mounted method executed");
  this.newStr = "3";
},
activated() {
  console.log("The actived method was executed...");
  this.newStr = "4";
}

Effect:

3. Dynamically set the keepAlive property

You can also set the keepAlive property in the vue file. It is only effective when added in the beforeRouteEnter() method, that is, add it in Home.vue when entering the page:

  // Use the guard in the component to do something with the page leaving event // to is the route to be redirected, from is the route of the previous page beforeRouteEnter(to, from, next) {
    to.meta.keepAlive = true;
    // The route continues to jump next();
  }

4. Use include and exclude to configure components that need to be cached

Configure in app.vue:

<router-view v-slot="{ Component }">
  <keep-alive include="testKA">
    <component :is="Component"/>
  </keep-alive>
</router-view>

Among them, testKA corresponds to the name of a component:

export default {
    name:'testKA', // keep-alive include attribute matches component name
    data() {return {}},
    activated() {
        // The life cycle of the keepalive cached page will be performed every time it is entered},
}

In addition, include usage is as follows:

<!-- Comma separated string -->
<keep-alive include="a,b">
  <component :is="view"></component>
</keep-alive>

<!-- Regular expression (using `v-bind`) -->
<keep-alive :include="/a|b/">
  <component :is="view"></component>
</keep-alive>

<!-- Array (using `v-bind`) -->
<keep-alive :include="['a', 'b']">
  <component :is="view"></component>
</keep-alive>

The usage of exclude is the same as that of include, representing components that are not cached.

5. Some pages need to be cached, and some pages need to be refreshed

Description: If there are three pages a, b, and c, when a->b, b refreshes the page, then b->c, c->b, b does not refresh the page, and then b->a, a->b, b refreshes the page.
Self-test, it can only be achieved with vuex, but the disadvantage is that the activated() method is not executed when the page is cached

6. Cache is only effective in the first-level routing

If you need to use cache in the secondary route, you can do the same configuration in the primary route

store.js code:

state: {
  keepAlives:[]
},
mutations:
  SET_KEEP_ALIVE(state,params) {
    state.keepAlives = params
  }
},
getters:{
  keepAlive:function(state){
    return state.keepAlives
  }
}

App.vue code:

<template>
  <div id="nav">
    <router-link to="/bbb">BBB</router-link> |
    <router-link to="/home">Home</router-link> |
    <router-link to="/about">About</router-link>
  </div>
  <router-view v-slot="{ Component }">
    <keep-alive :include="keepAlive">
      <component :is="Component"/>
    </keep-alive>
  </router-view>
</template>
<script>
  export default{
    computed:{
      keepAlive(){
        return this.$store.getters.keepAlive
      }
    }
  }
</script>

Home.vue code:

// Use the guard in the component to do something with the page leaving event // to is the route to be redirected, from is the route of the previous page beforeRouteEnter(to, from, next) {
  next(vm=>{
    if(from.path == "/bbb"){
      vm.$store.commit("SET_KEEP_ALIVE",["Home"])
    }
  });
},
beforeRouteLeave(to, from, next) {
  if (to.path == "/about") {
    console.log("You will be redirected to the /about page...")
  } else {
    console.log("You will be redirected to a non-/about page...")
    this.$store.commit("SET_KEEP_ALIVE",[])
  }
  // The route continues to jump next();
}

Effect:

Summarize

This is the end of this article about vue3 cache page keep-alive and unified routing processing. For more relevant vue3 cache page keep-alive content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Sample code for keeping-Alive with vue-router to achieve cache page effect
  • Detailed explanation of keep-alive + vuex to make cached pages flexible
  • Vue built-in component keep-alive event dynamic cache example
  • Vue project keepAlive cooperates with vuex to dynamically set routing cache mode

<<:  Sharing some details about MySQL indexes

>>:  Analysis of the implementation method of modifying the default network segment of Docker

Recommend

JS implements user registration interface function

This article example shares the specific code of ...

Detailed explanation of VUE responsiveness principle

Table of contents 1. Responsive principle foundat...

3 Tips You Must Know When Learning JavaScript

Table of contents 1. The magical extension operat...

Solution to MySql Error 1698 (28000)

1. Problem description: MysqlERROR1698 (28000) so...

Vue3 (V) Details of integrating HTTP library axios

Table of contents 1. Install axios 2. Use of axio...

A brief discussion on the VUE uni-app life cycle

Table of contents 1. Application Lifecycle 2. Pag...

VMWare15 installs Mac OS system (graphic tutorial)

Installation Environment WIN10 VMware Workstation...

Example analysis of the usage of the new json field type in mysql5.7

This article uses an example to illustrate the us...

Summary of common commands for Linux user and group management

This article summarizes the common commands for L...

Implementation steps for installing Redis container in Docker

Table of contents Install Redis on Docker 1. Find...

Explanation of factors affecting database performance in MySQL

A story about database performance During the int...

Detailed configuration of Nginx supporting both Http and Https

It is almost a standard feature for websites nowa...

MySQL online log library migration example

Let me tell you about a recent case. A game log l...

Detailed explanation of the use of Element el-button button component

1. Background Buttons are very commonly used, and...