About vue component switching, dynamic components, component caching

About vue component switching, dynamic components, component caching

background:

  • In the component-based development model, we will split the entire project into many components, and then organize them in a reasonable way to achieve the desired effect.
  • Because the page is organized by multiple components, there is naturally a problem of switching between components. Vue also proposes the concept of dynamic components, which allows us to better achieve the switching effect between components. However, the switching of components in Vue is actually the process of re-creating and destroying the components themselves. In some scenarios, we do not want the components to be recreated and re-rendered.

Actual scenario: User operates from list page --> detail page --> list page. The expected effect to be achieved at this time is that when the user switches from the detail page back to the list page, the original page remains unchanged instead of being re-rendered. At this time, the original list page needs to be cached when the user switches from the list page to the detail page.

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

1. Component switching method

Method 1: Use v-if and v-else

// When the variable 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>

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

// Click to switch login, registration, exit components <template>
     <div>
        <a href="#" 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" @click.prevent="comName = 'register'">Register</a>
        <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" @click.prevent="comName = 'logOut'">Log Out</a>
        
        // <component></component> to display the component with the corresponding name, which is equivalent to a placeholder // The :is attribute specifies the component name <component :is="comName"></component>
      </div>
    </template>

Method 3: vue-router

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

2. Component caching: keep-alive

Cache components as needed, rather than destroying and rebuilding them, as in the actual scenario at the beginning of this article

1.Keep-alive definition

When <keep-alive> is wrapped around a dynamic component, inactive component instances are cached instead of being destroyed.

<keep-alive> is an abstract component: it does not render a DOM element itself, nor does it appear in the parent component chain. When a component is switched within <keep-alive> , its activated and deactivated lifecycle hook functions will be executed accordingly.

2.Keep-alive life cycle

activated

Called when the keep-alive component is activated. This hook function is not called during server-side rendering.

deactivated

This hook is called when the keep-alive component is disabled. It is not called during server-side rendering.

Components created in keep-alive will have two more lifecycle hooks: activated and deactivated
Using 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 phase and take on the task of getting data in the original created hook function.

Note: These two lifecycle functions will only be called when the component is wrapped in keep-alive. If used as a normal component, they will not be called. After version 2.1.0, after using exclude, even if it is 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 that have cache set up:

  • First entry: beforeRouterEnter ->created->…->activated->…->deactivated> beforeRouteLeave
  • Subsequent entry: beforeRouterEnter ->activated->deactivated> beforeRouteLeave

3. How to use keep-alive

1. Props

include - string or array, regular expression. Only components with matching names will be cached --> the value of include is name of the component.
exclude - a string or regular expression. Any components with matching names will not be cached.
max : a number. The maximum number of components that can be cached.

2. Use with <component></component>

  <template>
     <div>
        <a href="#" 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" @click.prevent="comName = 'register'">Register</a>
        <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" @click.prevent="comName = 'logOut'">Log Out</a>
     
     // The login component will be cached. If include is not set, all components mounted to <component></component> will be cached by default. // Cache multiple specified components include = ['login', 'register']
      <keep-alive include="login">
          <component :is="comName"></component>
      </keep-alive>    
      </div>
    </template>

3. Use with <router-view /> routing

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

 {
    path: '/login',
    name: 'login',
    component: () => import('../views/login.vue')
    meta:{
        keepAlive : true // login component will be cached}
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/register.vue'),
      meta:{
        keepAlive : false // register component will not be 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 need caching --> 
    <router-view v-if="!$route.meta.keepAlive"> </router-view>
</div>

4. Clear cache components

 // beforeRouteLeave() hook // Determine whether 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();
    }

This is the end of this article about vue component switching, dynamic components, and component caching. For more relevant vue component switching, dynamic components, and component caching content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Implementation of Vue dynamic components and v-once directive
  • Detailed explanation of vue.js dynamic components
  • Vue uses dynamic components to achieve TAB switching effect
  • How does Vue3's dynamic components work?
  • In-depth understanding of Vue dynamic components and asynchronous components
  • Vue components dynamic components detailed explanation

<<:  Introduction to MySQL role functions

>>:  How to choose and use PNG, JPG, and GIF as web image formats

Recommend

Solution to web page confusion caused by web page FOUC problem

FOUC is Flash of Unstyled Content, abbreviated as ...

How to use IDEA to create a web project and publish it to tomcat

Table of contents Web Development 1. Overview of ...

Detailed explanation of the payment function code of the Vue project

1. Alipay method: Alipay method: Click Alipay to ...

How to set the memory size of Docker tomcat

When installing Tomcat in Docker, Tomcat may over...

Installation tutorial of the latest stable version of MySQL 5.7.17 under Linux

Install the latest stable version of MySQL on Lin...

A brief discussion on MySQL B-tree index and index optimization summary

MySQL's MyISAM and InnoDB engines both use B+...

Install Docker on CentOS 7

If you don't have a Linux system, please refe...

WeChat applet development chapter: pitfall record

Recently, I participated in the development of th...

Resolving MySQL implicit conversion issues

1. Problem Description root@mysqldb 22:12: [xucl]...

How to implement input checkbox to expand the click range

XML/HTML CodeCopy content to clipboard < div s...

Detailed explanation of system input and output management in Linux

Management of input and output in the system 1. U...

Solve the problem of inconsistent front and back end ports of Vue

Vue front and back end ports are inconsistent In ...

How to optimize the slow Like fuzzy query in MySQL

Table of contents 1. Introduction: 2. The first i...