Component cache keep-alive

The purpose of component caching: (generally completed in this step of project optimization) 

  • Prevent components from being created and destroyed frequently
  • Prevent repeated useless execution of network requests

step

Component cache, which can maintain the state of components.

Combined with vue's built-in keep-alive component, the state of the component can be maintained.

Official document address: https://cn.vuejs.org/v2/api/#keep-alive

  1. Put a keep-alive component on the outer layer of router-view in App.vue

    • The cached first-level routing page switch is not released, but the home page will still request data again (because the home page is in the second-level route)
  2. Put a keep-alive component on the outer layer of router-view in Layout.vue

    • This time the Home and My pages are cached (the secondary routing is also managed)
  3. But found that the search page (under the first-level routing) and the details page (under the first-level routing) were mostly cached (entering different articles many times, and found that they were all the same article details)

  4. Use the exclude attribute for router-view to distinguish which page components can be cached

    == Pay special attention to the name of the component in exclude (it has nothing to do with routing) ==

    <template>
      <div id="app">
        <!-- 一级路由窗口 -->
        <keep-alive
          exclude="ArticleIndex,search,UserProfile,favoriteArticle,HistoryAticle,fens"
        >
          <router-view></router-view>
        </keep-alive>
      </div>
    </template>

    Of course, you can also set exclude on the secondary route

<template>
  <div class="layout-container">
    <!-- 二级路由出口 -->
    <keep-alive exclude="my">
      <router-view> </router-view>
    </keep-alive>
  </div>
</template>
<script>

summary

  • Only components that are destroyed by switching need to be cached
  • router-view is the mount point when they switch, and it is set outside the mount point to cache internal components

 important point:

The component is cached, and if it is cut away, it will lose its activation. The life cycle method triggers deactivated

  None is cached, cut away, destroyed destroys the life cycle method trigger

Guess you like

Origin blog.csdn.net/m0_65812066/article/details/128619250