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

Specific use of MySQL segmentation function substring()

There are four main MySQL string interception fun...

Solutions to Files/Folders That Cannot Be Deleted in Linux

Preface Recently our server was attacked by hacke...

Implementation of multi-environment configuration (.env) of vue project

Table of contents What is multi-environment confi...

Detailed tutorial on installing Protobuf 3 on Ubuntu

When to install If you use the protoc command and...

How to use node scaffolding to build a server to implement token verification

content Use scaffolding to quickly build a node p...

MySQL server 5.7.20 installation and configuration method graphic tutorial

This article records the installation and configu...

How to install MySQL 5.7.17 and set the encoding to utf8 in Windows

download MySQL official download, select Windows ...

Talk about how to identify HTML escape characters through code

Occasionally you'll see characters such as &#...

Analysis and solution of a.getAttribute(href,2) problem in IE6/7

Brief description <br />In IE6 and 7, in a ...

Detailed explanation of JS browser storage

Table of contents introduction Cookie What are Co...

How to connect Django 2.2 to MySQL database

1. The error information reported when running th...

Automatic file synchronization between two Linux servers

When server B (172.17.166.11) is powered on or re...