Detailed explanation of the function and usage of keepAlive component in Vue

Detailed explanation of the function and usage of keepAlive component in Vue

Preface

During the interview, many interviewers may mention Vue when asking, do you know what keep-alive does?

keep-alive is a built-in component of vue, and the function of this component is to cache inactive components. We know that in general, when a component is switched, it will be destroyed by default. If there is a demand, a component will not be destroyed after switching, but the previous state will be saved, then keep-alive can be used to achieve

<keep-alive> is a built-in component of Vue, which can keep the state in memory during component switching to prevent repeated rendering of DOM.

<keep-alive> When wrapping 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 parent component chain.

After I use the scaffolding to create a project, two components, home and about, will be generated, and they will be switched through routing.

Home Component

<template>
  <div class="home">
    <input type="text">
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'home',
  components:
    HelloWorld
  }
}
</script>

I wrote an input box in the home component

about component

<template>
  <div class="about">
    <input type="text">
  </div>
</template>
<script>
export default {
  name:"about"
}
</script>

The same about component also puts an input box

When we enter something in the input box of the home component, then switch to the about component, and then switch back to the home component, we will find that the previously entered content has been cleared. In fact, it is easy to understand that when switching to the about component, the home component is destroyed and the value of the input box is naturally cleared.

I wrote the destroyed lifecycle function in the home component

When switching to the about component, the destroyed of the home component is triggered, so the home component is destroyed.

Then we can use the keep-alive component to wrap the router-view component and cache the inactive components.

App Components

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>
    </div>
    <keep-alive>
      <router-view />
    </keep-alive>
    
  </div>
</template>

After writing, you will find that when switching to the about component, the destroyed in the home component is not triggered, and the value of the home component is also saved.

But this is definitely not good. We will find that the value of the about component is also cached, that is, all routing components are cached, which seriously wastes performance and does not meet the requirements. Now we only want to cache the home component.

There are two properties on keep-alive

A string or a regular expression. Only matching components will be cached.

  • Include value is a string or a regular expression matching the component name will be cached.
  • The exclude value is a string or regular expression that matches the component name and will not be cached.

First, use include to match the name defined in the component and cache it.

<keep-alive include="home">
   <router-view />
</keep-alive>

We will find that home has been cached, but about has not been cached

And exclude is to exclude, this will not be demonstrated, it is very simple, in addition to this we can also use the meta attribute in the route to control

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

Add the keepAlive attribute to true in the meta of the home routing rule clock, which means that the current routing component needs to be cached

The keep-alive code can be combined with v-if to wrap it. If the keepAlive in meta is true, it will be cached, otherwise it will not be cached. This can be more flexible.

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

In this way, component caching is implemented, but there are still some problems. Because the component is cached and not destroyed, the component will not be recreated when switching, and naturally the life cycle functions such as create will not be called. Therefore, activated and deactivated should be used to obtain whether the current component is active.

I wrote the activated and deactivated lifecycle functions in the home component

activated(){
    console.log("Oh, you saw me")
    console.log("----------activated--------")
  },
  deactivated(){
    console.log("Hate it!! You left again")
    console.log("----------deactivated--------")
  }

I believe you can see it clearly through the gif above. At this time, keep-alive is almost done.

Summarize

This is the end of this article about the role and usage of the keepAlive component in Vue. For more information about the usage of the keepAlive component in Vue, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

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

<<:  Example usage of Linux compression file command zip

>>:  mysql5.5.28 installation tutorial is super detailed!

Recommend

How to set up Windows Server 2019 (with pictures and text)

1. Windows Server 2019 Installation Install Windo...

A brief talk about calculated properties and property listening in Vue

Table of contents 1. Computed properties Syntax: ...

Solution to the problem "Table mysql.plugin doesn't exist" when deploying MySQL

Today I deployed the free-installation version of...

Implementation of code optimization for Vue2.x project performance optimization

Table of contents 1 Use of v-if and v-show 2. Dif...

Pure CSS to achieve candle melting (water droplets) sample code

Achieve results Implementation ideas The melting ...

How to query a record in Mysql in which page of paging

Preface In practice, we may encounter such a prob...

25 div+css programming tips and tricks

1. The ul tag has a padding value by default in M...

Implementation of mysql backup strategy (full backup + incremental backup)

Table of contents Design scenario Technical Point...

Zabbix3.4 method to monitor mongodb database status

Mongodb has a db.serverStatus() command, which ca...

Analysis of the process of building a LAN server based on http.server

I don’t know if you have ever encountered such a ...

Summary of some problems encountered when integrating echarts with vue.js

Preface I'm currently working on the data ana...