Blog Background:

  • In componentized development, we break the whole project into many components and organize them in a reasonable way to achieve the desired results

  • Because pages are organized into multiple components, switching between components is a natural problem, The concept of dynamic component is also proposed in Vue, which enables us to better realize the switching effect between components. However, the switching of components in Vue is actually a process of re-creation and destruction of components. In some scenarios, we do not want components to be re-created and re-rendered

  • Actual scenario: The user operates the list page -> Details page -> List page. The expected effect is that the original page remains unchanged when the user switches from the details page to the list page, rather than re-rendering. In this case, the original list page needs to be cached when the user switches from the list page to the details page

  • This article focuses on switching components and caching solutions in Vue

1. Component switchover mode

Method 1: UseV - if and v - else

// If flag is true, the comp-a component is displayed; otherwise, the comp-b component is displayed
<comp-a v-if="flag"></comp-a>

<comp-b v-else></comp-b>
Copy the code

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

// Click toggle login, register, and exit components
   <template>
     <div>
        <a href="#" @click.prevent="comName = 'login'">The login</a>
        <a href="#" @click.prevent="comName = 'register'">registered</a>
        <a href="#" @click.prevent="comName = 'logOut'">exit</a>
        
        //  <component></component>To display the component with the corresponding name, which is equivalent to a placeholder // :is property specifying the component name<component :is="comName"></component>
      </div>
    </template>
Copy the code

Three:vue-router

// Routing rules:
  {
    path: '/login'.name: 'login'.component: () = > import('.. /views/login.vue')}, {path: '/register'.name: 'register'.component: () = > import('.. /views/register.vue')},// Where the component needs to be displayed:
   <router-view />
Copy the code

Component cache: keep-alive

Components are cached on demand, rather than destroyed and rebuilt, as illustrated in the actual scenario at the beginning of this article

1.keep-aliveDefinition:


  • when wrapping dynamic components, inactive component instances are cached rather than destroyed.


  • is an abstract component: it does not render a DOM element on its own and does not appear in the parent component chain. When a component is switched within

    , its activated and deactivated lifecycle hook functions are executed accordingly.

2.keep-aliveLife cycle of

1. The activated

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

2. The deactivated

Calling this hook when the keep-alive component is disabled is not called during server-side rendering

  • Components created within keep-alive have two more lifecycle hooks: activated and deactivated
  • If keep-alive is used, data is stored in memory. To obtain the latest data each time a page is entered, data needs to be obtained in the Activated phase, which is responsible for obtaining data in the original Created hook function.

Note: These two life cycle functions will only be called if the component is wrapped in keep-alive. They will not be called if the component is used as a normal component. After version 2.1.0, exclude will exclude the component even if it is wrapped in keep-alive. These two hook functions will still not be called! In addition, this hook function is not called during server-side rendering.

  • Component with cache set:

BeforeRouterEnter ->created->… – > activated – >… ->deactivated> beforeRouteLeave

Follow-up Access: beforeRouterEnter -> Activated -> DeActivated > beforeRouteLeave

3.keep-aliveMethod of use

1.Props

  • Include – string or array, regular expression. Only components whose names match are cached –>include is the name of the component.
  • Exclude – a string or regular expression. Any component with a matching name will not be cached.
  • Max – Numbers. Maximum number of components can be cached.

2. The collocation<component></component>use

  <template>
     <div>
        <a href="#" @click.prevent="comName = 'login'">The login</a>
        <a href="#" @click.prevent="comName = 'register'">registered</a>
        <a href="#" @click.prevent="comName = 'logOut'">exit</a>// Login components will be cached without setting include to cache all mounted to by default<component></component>Include = ['login','register']<keep-alive include="login">
          <component :is="comName"></component>
      </keep-alive>    
      </div>
    </template>
Copy the code

Match 3.<router-view />Routing using

The keepAlive attribute of the route meta information needs to be configured. The keepAlive code can be wrapped with V-if. If the keepAlive value in the meta is true, the keepAlive code is cached

 {
    path: '/login'.name: 'login'.component: () = > import('.. /views/login.vue')
    meta: {keepAlive : true   // The login component is cached}}, {path: '/register'.name: 'register'.component: () = > import('.. /views/register.vue'),
      meta: {keepAlive : false   // The register component is not cached}},Copy the code

<router-view />:

<div id="app">
    <keep-alive> 
    <! -- View components that need caching -->
        <router-view v-if="$route.meta.keepAlive"> </router-view>
    </keep-alive><! -- View component without cache --><router-view v-if=! "" $route.meta.keepAlive"> </router-view>
</div>

Copy the code

4. Clear cache components

BeforeRouteLeave (to, from,); beforeRouteLeave(to, from,); next) { if (to.path === "/goods_detail") { from.meta.keepAlive = true; } else { from.meta.keepAlive = false; // this.$destroy() } next(); }Copy the code