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

Detailed explanation of nmcli usage in CentOS8

Common nmcli commands based on RHEL8/CentOS8 # Vi...

getdata table table data join mysql method

public function json_product_list($where, $order)...

MySQL 8.0.18 adds users to the database and grants permissions

1. It is preferred to use the root user to log in...

Detailed explanation of how to implement secondary cache with MySQL and Redis

Redis Introduction Redis is completely open sourc...

JS implements the snake game

Table of contents 1. Initialization structure 2. ...

Install multiple versions of PHP for Nginx on Linux

When we install and configure the server LNPM env...

Understanding and example code of Vue default slot

Table of contents What is a slot Understanding of...

Detailed explanation of the use of MySQL paradigm

1. Paradigm The English name of the paradigm is N...

HTML hyperlink style (four different states) setting example

Copy code The code is as follows: <style type=...

Vue-cli framework implements timer application

Technical Background This application uses the vu...

Learn Node.js from scratch

Table of contents url module 1.parse method 2. fo...

Mysql delete data and data table method example

It is very easy to delete data and tables in MySQ...

How does Zabbix monitor and obtain network device data through ssh?

Scenario simulation: The operation and maintenanc...