Example of using Vue built-in component keep-alive

Example of using Vue built-in component keep-alive

keep-alive is one of Vue's built-in components, mainly used to preserve component status or avoid re-rendering.

effect

Keep the state in memory during component switching to prevent repeated DOM rendering, reduce loading time and performance consumption, and improve user experience.

1. Usage of keep-alive

When <keep-alive> is wrapped around a dynamic component, inactive component instances are cached instead of being destroyed.
Similar to <transition>, <keep-alive> is an abstract component: it does not render a DOM element itself, nor does it appear in the component's parent component chain.

When a component is switched within <keep-alive>, its activated and deactivated lifecycle hook functions will be executed accordingly.

Props:

include - a string or a regular expression. Only components with matching names will be cached.
exclude - a string or regular expression. Any components with matching names will not be cached.
max : a number. The maximum number of component instances that can be cached.

  • include & exclude

If you only want to cache the state of some components, you can use the include property.

If you want to exclude some components so that others are cached, use the exclude attribute.

  • max

The maximum number of component instances that can be cached. Once this number is reached, the cached component instance that has not been accessed in the longest time will be destroyed before a new instance is created.

<keep-alive :max="10">
  <component :is="view"></component>
</keep-alive>

Example of use:

1. Cache all pages:

<keep-alive>
    <router-view></router-view>
    <!--Here are the components that will be cached-->
</keep-alive>

2. Cache some pages based on conditions

(For more usage, see the official website API)

<template>
  <div id="app">
  	// 1. Cache components named newsList or productList <keep-alive include='newsList,productList'>
         <router-view/>
      </keep-alive>
	
	// 2. The component named test will not be cached <keep-alive exclude='test'>
  	  <router-view/>
	</keep-alive>
  </div>
</template>
<script>
export default {
  name: 'App'
}
</script>

Notice:

There is one more step. You must add a name attribute to the component in the script section of the component whose state needs to be cached. If you do not use keep-alive cache components, you do not need to write the name attribute. However, if keep-alive is used to cache the component state, this component must have this property. In addition, the value of this attribute must be exactly the same as the value of the include attribute in the tag, including uppercase and lowercase. Take productList.vue component as an example

<template>
    <!-- Here is the HTML structure of the productList component-->
</template>
<script>
export default {
    name: "productList", //If keep-alive is used to cache the component status, this component must have this attribute.
    data(){
        return {}
    }
</script>

3. Combine vue-router to cache some pages

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home,
      children: [
        {
          path: 'products',
          name: 'products',
          component: products,
          meta: {
        	keepAlive: true // caching required }
        },
        {
          path: 'newsDetails',
          name: 'newsDetails',
          component: newsDetails,
          meta: {
        	keepAlive: false // No caching required }
        }
      ]
    }
  ]
})

In App.vue

<template>
  <div id="app">
    <keep-alive>
      <router-view v-if="$route.meta.keepAlive"></router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive"></router-view>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

2. Keep-alive life cycle

The components created in keep-alive will have two more lifecycle hooks: activated and deactivated.

1. activated

Called when the keep-alive component is activated.

This is called the first time the component is rendered, and then every time the cached component is activated.

The first time you enter a cached route/component, after mounted, before the beforeRouteEnter guard is called before the callback function passed to next:

When the page is first entered, the order of hook triggering is created->mounted->activated

Because the component is cached, these hooks will not be triggered when entering the cache route/component again:

beforeCreate created and beforeMount mounted will not be triggered.

2. deactivated

Called when the keep-alive component is deactivated (leaves the route).

If keep-alive is used, beforeDestroy (hook before component destruction) and destroyed (component destruction) will not be called, because the component is not destroyed but cached.

This hook can be seen as a replacement for beforeDestroy. If you cache a component and want to do something when the component is destroyed, you can put it in this hook.

Notice:

1. Using keep-alive will keep the data in memory. If you want to get the latest data every time you enter the page, you need to get the data in the activated stage and take on the task of getting data in the original create hook function.

2. These two lifecycle functions will only be called when the component is wrapped in keep-alive. If used as a normal component, they will not be called. After version 2.1.0, after using exclude, even if it is wrapped in keep-alive, these two hook functions will still not be called!

3. The above two hook functions are not called during server-side rendering.

Refer to the official documentation: cn.vuejs.org/v2/api/#kee…

The above is the detailed usage example of Vue's built-in component keep-alive. For more information about Vue's built-in component keep-alive, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of how to use Teleport, a built-in component of Vue3
  • Use of LRU algorithm in Vue built-in component keep-alive
  • Use of keep-alive component of vue.js built-in component
  • Detailed explanation of the use of Vue's new built-in components

<<:  MySQL database green version installation tutorial to solve system error 1067

>>:  Use of Zabbix Api in Linux shell environment

Recommend

React+Antd implements an example of adding, deleting and modifying tables

Table of contents Table/index.js Table/model/inde...

64-bit CentOs7 source code installation mysql-5.6.35 process sharing

First install the dependent packages to avoid pro...

JavaScript realizes the drag effect of modal box

Here is a case of modal box dragging. The functio...

How to enable or disable SSH for a specific user or user group in Linux

Due to your company standards, you may only allow...

Solution to occasional crash of positioning background service on Linux

Problem Description In the recent background serv...

Use HTML to write a simple email template

Today, I want to write about a "low-tech&quo...

Detailed explanation of InnoDB storage files in MySQL

Physically speaking, an InnoDB table consists of ...

Mini Program to Implement Paging Effect

This article example shares the specific code for...

Linux hardware configuration command example

Hardware View Commands system # uname -a # View k...

Implementation of nginx flow control and access control

nginx traffic control Rate-limiting is a very use...

Detailed explanation of CSS counter related attributes learning

The CSS counter attribute is supported by almost ...

Sample code for highlighting search keywords in WeChat mini program

1. Introduction When you encounter a requirement ...

Detailed explanation of Linux file operation knowledge points

Related system calls for file operations create i...

How to publish static resources in nginx

step Place the prepared static resource files in ...

Difference between var and let in JavaScript

Table of contents 1. Scopes are expressed in diff...