About vue component switching dynamic components component caching

  • 2021-12-04 17:55:08
  • OfStack

Directory 1. Component Switching Mode 1: Use v-if and v-else Mode 2: Use built-in components: < component > < /component > Mode 3: vue-router2. Component cache: keep-alive1. keep-alive definition 2. keep-alive lifecycle 3. keep-alive usage 1. Props2. Match < component > < /component > Use 3. Match < router-view / > Routing usage 4. Clear the cache component

Background:

In the component-based development mode, we will split the whole project into many components, and then organize them in a reasonable way to achieve the expected results Because pages are organized in multiple components, At this time, there is a problem of switching between components. Vue also puts forward the concept of dynamic components, which makes us better realize the switching effect between components. However, the switching of components in vue is actually a process of recreating and destroying components themselves. In some scenarios, we don't want components to be recreated and rendered again

Actual scenario: User action list page- > Details page- > The expected effect of the list page is that the original page remains unchanged when the user switches from the details page to the list page, instead of rendering it again, so the original list page needs to be cached when the user switches from the list page to the details page

This paper mainly introduces the switching of components in Vue and the solution of cache

1. How to switch components

Mode 1: Use v-if and v-else


//  Variable flag For true Display when comp-a Component  , On the contrary, it shows comp-b Component 
<comp-a v-if="flag"></comp-a>

<comp-b v-else></comp-b>

Mode 2: Use built-in components: < component > < /component >


//  Click Switch Login , Registration , Exit component 
   <template>
     <div>
        <a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  @click.prevent="comName = 'login'"> Login </a>
        <a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  @click.prevent="comName = 'register'"> Registration </a>
        <a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  @click.prevent="comName = 'logOut'"> Quit </a>
        
        //  <component></component>  To show the component with the corresponding name , Equivalent to 1 Placeholder 
        //    :is  Property specifies   Component name 

      <component :is="comName"></component>
      </div>
    </template>

Mode 3: vue-router


//  Routing rules :
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/register.vue')
  },
  
  //  You need to show the location of the component :
   <router-view />

2. Component cache: keep-alive

Components are cached on demand, not destroyed and rebuilt, as in the actual scenario exemplified at the beginning of this article

1. Definition of keep-alive

<keep-alive> When wrapping dynamic components, inactive component instances are cached instead of destroyed.

< keep-alive > Is an abstract component: It does not render an DOM element by itself, nor does it appear in the parent component chain. When the component is in the <keep-alive> Inside is switched, and its activated And deactivated These two lifecycle hook functions will be executed correspondingly.

2. Life cycle of keep-alive

activated

In keep-alive The hook function called when the component is activated is not called during server-side rendering

deactivated

In keep-alive When the component is deactivated, the hook is not called during server-side rendering

Be contained in keep-alive There are two more lifecycle hooks in the component created in: activated And deactivated
Use keep-alive The data will be kept in memory. If you want to get the latest data every time you enter the page, you need to get the data in activated stage and bear the original <keep-alive> 0 The task of retrieving data in a hook function.

Note: These two lifecycle functions will only be called if the component is wrapped in keep-alive, and will not be called if used as a normal component, and after version 2.1. 0, after using exclude exclusion, even if wrapped in keep-alive, these two hook functions will still not be called! In addition, this hook function will not be called when rendering on the server side.

Components with cached settings:

First entry: beforeRouterEnter ->created->…->activated->…->deactivated> beforeRouteLeave On subsequent entry: beforeRouterEnter ->activated->deactivated> beforeRouteLeave

3. How to use keep-alive

1.Props

include -Strings or arrays, regular expressions. Only components with matching names will be cached- > include Is the value of the component name .
exclude -A string or regular expression. Any components with matching names will not be cached.
max -Numbers. How many components can be cached at most.

STEP 2 Match < component > < /component > Use


  <template>
     <div>
        <a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  @click.prevent="comName = 'login'"> Login </a>
        <a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  @click.prevent="comName = 'register'"> Registration </a>
        <a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  @click.prevent="comName = 'logOut'"> Quit </a>
     
     // login Components are cached   Do not set include Will default cache all mounts to the <component></component> Components of 
     //  Cache multiple specified components include = ['login','register']
      <keep-alive include="login">
          <component :is="comName"></component>
      </keep-alive>    
      </div>
    </template>

STEP 3 Match < router-view / > Routing usage

Routing needs to be configured meta Informational keepAlive Attribute
keep-alive The code can be wrapped in conjunction with v-if, if the keepAlive For true Cache, no side do not cache, this can be more flexible 1


 {
    path: '/login',
    name: 'login',
    component: () => import('../views/login.vue')
    meta:{
        keepAlive : true   // login Components are cached 
    }
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/register.vue'),
      meta:{
        keepAlive : false   //  register Components are not cached 
    }
  },

< router-view / > :


<div id="app">
    <keep-alive> 
    <!--  View components that need to be cached  -->
        <router-view v-if="$route.meta.keepAlive"> </router-view>
    </keep-alive>
    
    <!--  View components that do not require caching  --> 
    <router-view v-if="!$route.meta.keepAlive"> </router-view>
</div>

4. Clear the cache component


 // beforeRouteLeave() Hook 
//  Determine if you want to go to the details page 
  beforeRouteLeave(to, from, next) {
      if (to.path === "/goods_detail") {
        from.meta.keepAlive = true;
      } else {
        from.meta.keepAlive = false;
        // this.$destroy()
      }
      next();
    }

Related articles: