Detailed explanation of keepAlive usage in Vue front-end development

Detailed explanation of keepAlive usage in Vue front-end development

Preface

keep-alive is a built-in component of Vue. When it is wrapped around a dynamic component, it caches inactive component instances instead of destroying them.

During component switching, the state is retained in memory to prevent repeated DOM rendering, reduce loading time and performance consumption, and improve user experience. How to use

<keep-alive>
    <component />
</keep-alive>

The component here will be cached.

keep-avlive hook function

Components created in keep-alive will have two more lifecycle hooks: activated and deactivated. activated: called when the keep-alive component is activated. 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, taking on the task of getting data in the original create hook function.
deactivated: called when the keep-alive component is deactivated. If keep-alive is used, the beforeDestory and destroyed hooks will not be called, because the component is not destroyed but cached. Therefore, the deactivated hook can be regarded as a substitute for beforeDestory and destroyed, such as clearing localStorge data.

keep-avlive caches which components

There are two ways to cache components in keep-avlive. One is to use the include and exclude properties provided by the keep-avlive component to match the corresponding components through parameters for caching. The other is to set the meta attribute in the route.
Use include and exclude properties to complete cache component settings

/* Will cache the component named test*/
<keep-alive include='test'>
      <router-view/>
</keep-alive>

Use include to cache the component named test.

<keep-alive exclude="test"> 
  <router-view/>
</keep-alive>

Using exclude, the component named test will not be cached.
Use the meta attribute in the route to set the cache component, such as

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

The goods component needs to be cached, but ratings does not. Use the following statement to dynamically complete the component cache setting. The setting code is as follows

<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>

Example

Set up two components, KeepCom1 and KeepCom2. Set cache for KeepCom1 and do not set cache for KeepCom2. Test the use of two hook functions at the same time. Here, routing meta is used to implement the setting of cache components.
KeepCom1 code is as follows:

<template>
  <div class="wrapper">
    <ul class="content"></ul>
    <button class="add" id="add" @click="add">Add child element</button>
  </div>
</template>
<script>
export default {
  name: 'keepCom1',
  methods: {
    add () {
      let ul = document.getElementsByClassName('content')[0]
      let li = document.createElement('li')
      li.innerHTML = 'I am adding an element'
      ul.appendChild(li)
    }
  },
  activated () {
    console.log('cache activated execution')
  },
  deactivated () {
    console.log('cache deactivated execution')
  }
}
</script>
<style>
</style>

KeepCom2 code is as follows:

<template>
  <div class="wrapper">
    <ul class="content"></ul>
    <button class="add" id="add" @click="add">Add child element</button>
  </div>
</template>

<script>
export default {
  name: 'keepCom2',
  methods: {
    add () {
      let ul = document.getElementsByClassName('content')[0]
      let li = document.createElement('li')
      li.innerHTML = 'I am adding an element'
      ul.appendChild(li)
    }
  },
  activated () {
    console.log('cache activated execution')
  },
  deactivated () {
    console.log('cache deactivated execution')
  }
}
</script>
<style>
</style>

The codes of KeepCom1 and KeepCom2 are basically the same, which is to add nodes to the page.
The keepAvliveTest code is as follows

<template>
  <div align="center" style="margin-top: 20px;">
    <router-link to="/keepAvliveTest/keepcom1">Use cache</router-link>
    <router-link to="/keepAvliveTest/keepcom2">Do not use cache</router-link>
    <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: 'keepAvliveTest'
}
</script>
<style>
</style>

Complete the switch between keepcom1 and keepcom2 components. The result after execution is

insert image description here

keepcom1 uses cache. When switching pages, the three elements added last time are still there, and the hook function is executed. Keepcom2 does not use cache. When switching pages, an element added last time no longer exists and is restored to its initial state. And both hooks are not getting executed.

Summary and Notes

When setting up pages that need to be cached, it is recommended to use the meta tag in the router so that the code is less coupled. keep-alive first matches the name field of the included component. If name is not available, it matches the registered name in the components configuration of the current component. Included in keep-alive, but meets exclude, activated and deactivated will not be called

The above is the detailed content of the detailed explanation of the use of keepAlive in vue front-end development. For more information about vue front-end, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Instructions for using keepAlive in Vue projects (super practical version)
  • Detailed explanation of vue keepAlive cache clearing problem case
  • Detailed explanation of keepAlive use cases in Vue
  • Detailed explanation of the function and usage of keepAlive component in Vue
  • Solve the problem of not caching when using keepAlive in Vue
  • Vue keepsAlive setting does not take effect and its solution

<<:  Docker configuration Alibaba Cloud Container Service operation

>>:  Use of MySQL stress testing tool Mysqlslap

Recommend

Pure JavaScript to implement the number guessing game

Develop a number guessing game that randomly sele...

MySQL 8.0.16 installation and configuration tutorial under Windows 10

This article shares with you the graphic tutorial...

Tutorial on downloading, installing, configuring and using MySQL under Windows

Overview of MySQL MySQL is a relational database ...

JavaScript article will show you how to play with web forms

1. Introduction Earlier we introduced the rapid d...

CSS flex several multi-column layout

Basic three-column layout .container{ display: fl...

React sample code to implement automatic browser refresh

Table of contents What is front-end routing? How ...

Nexus private server construction principle and tutorial analysis

one. Why build a Nexus private server? All develo...

Detailed usage of Linux text search command find

The find command is mainly used to find directori...

Some indicators of excellent web front-end design

The accessibility of web pages seems to be somethi...

React example showing file upload progress

Table of contents React upload file display progr...

3 Tips You Must Know When Learning JavaScript

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

This article will show you what Vite does to the browser's request

Table of contents Working principle: What does th...