When building a SPA application, a common scenario is that the list page jumps to the details page, but the details page falls back to the list page, and the list page is refreshed.

How do I make sure I don’t refresh the page when I go back? Keep-alive is a very good solution (of course you can also override it with subrouting, absolute positioning situations *_*).

Keep – the role of the alive

Keep-alive is a built-in component of Vue that keeps state in memory during component switching, preventing repeated DOM rendering.

Keep-alive this passage is mainly about the use of keep-alive.

Keep the usage – the alive

Load dynamic components like Tabs.

Cache components

<keep-alive> <component include="a" exclude="b"> <! -- Component with name a will be cached! The component whose name is B is not cached! --> </component> </keep-alive>Copy the code

The routing cache

<keep-alive include="a"> <router-view> <! Only view A components whose path matches will be cached! --> </router-view> </keep-alive>Copy the code

Recommended usage: There is no need to cite component names that need to be cached

<keep-alive> <router-view v-if="$route.meta.keepAlive"> <! -- Here are the view components that will be cached, such as Home! --> </router-view> </keep-alive> <router-view v-if="! $route.meta.keepAlive"> <! -- Here are view components that are not cached, such as Edit! --> </router-view>Copy the code

Keep-alive includes the original component, not the slot of the normal component. Keep-alive is just an abstract component. For more details, see vue Keep-Alive (2) : Anatomy of the Implementation Principle of Keep-Alive — Learning Note Organizing.

Keep – props of the alive

  • Include-string or regular expression. Only matching components are cached

  • Exclude – a string or regular expression. Any matching component will not be cached

  • Max – The maximum number of cache components, beyond which LRU’s policy is used to replace cached data.

Keep-alive + VUE component declaration period + route guard

The purpose of keep-alive is to cache the component in memory (without letting it be destroyed) and keep all of its states until the next rendering.

Note: The actual memory is not the rendered HTML node string, but the VUE compiled and virtualized DOM object.

The goal is to prevent repeated DOM rendering, which triggers DIff updates to the VM when the data changes.

All functions of VUE are implemented around its life cycle. Calling corresponding hook functions at different stages of the life cycle can realize two important functions of component data management and DOM rendering.

Keep-alive caches components, but it also blocks the normal lifecycle flow of vUE.

The vUE lifecycle is: BeforeCreate, created, beforeMonted, mounted, beforUpdate, update, beforDestroy, destroyed, details see the summary vue2. X into the pit – review contrast angularJS/React”

Some requested data is requested when switching between pages/components, and each request results in repeated rendering affecting performance. The data can be stored in the cache — at this point the components are wrapped with keep-alive, but the above eight lifecycle hooks are invalidated.

Instead, activate and Deactivated are activated and, in versions 2.2.0 and later, activated and deactivated will trigger in all nested components within the tree.

  • Activate: a lifecycle hook that is used when the wrapped component is activated (activated every time the component is invoked, including the first time).

  • Enter the cache route/component for the first time: beforeRouteEnter > beforeCreate > Created > Mounted > Activated >… . > beforeRouteLeave > deactivated

  • Enter the component again: beforeRouteEnter > Activated >… . > beforeRouteLeave > deactivated

  • Deactivated: Called when the wrapped component is no longer in use

Theory: When introducing keep-alive into a project,

  • Created – mounted – activated

  • Deactivated is triggered during exit.

  • On re-entry (forward or backward), only Activated is triggered. If created or Mounted handles a refreshed page, this hook is not called and cannot be refreshed.

BeforeRouteEnter always fires

  • When keep-alive is not used,

    beforeRouteEnter –> created –> mounted –> destroyed

  • When using keep-alive,

    beforeRouteEnter –> created –> mounted –> activated –> deactivated

More pits, recommended to see

Vue Lifecycle Complete Solution (vueRouter, Keep-alive, Lifecycle)

“Vue pit Climbing tour — keepAlive and Vue-Router combined to realize page caching and remember the scrolling position function and some points need to pay attention to”

Keep-alive activate is applied to the project

How easy is it to not just click to the details page and go straight back

State the refresh

For example, when you add shopping cart to the details page, the list page needs to show the number of cars purchased, etc., which needs to be combined with Vuex.

What’s more, every time you go to this page, you have to ask for some data in the background, which you need to do inside Activate

Found a colleague implementation is: the page leaves, settimeout, guess a time to notify the list page, to perform operations. This one, well, works, but it’s definitely not going to work!

Scrollbar reset

You can solve this problem by using the vue-keep-scrollposition component. This component, however, only has a container for refreshing routes. What if it’s a list on the page that needs to be refreshed?

Store scrollbar location information in pages that need caching, such as beforeRouteLeave for list pages. The other operating principles are similar.

/ / leave beforeRouteLeave (to: any, the from: any, next: any) {/ / let the dom: HTMLElement | null = document. The getElementById (' list '); let dom = this.$refs.list; // When you leave, try to store the scroll position. to.meta.scrollTop = dom.scrollTop; Const scrollTop = this.$route.meta. ScrollTop; if (scrollTop) { this.$nextTick(() => { this.$refs.list.scrollTop = scrollTop; }); }}Copy the code

The important thing here is not to refresh the scroll bar position information in real time on the list page by listening for scroll events – there is no necessary performance cost.

Keep-alive cache page limit

Only when you roll back from page B to page A, the cache status before page A is restored. Let me give you a common case

To jump from the panel page to the edit page, you need to cache the panel page. That is: from the edit page back to the panel page, the panel page is the same as before.

Panel page

export default [
  {
    path: '/panel/:biz_id',
    name: 'panel',
    component: () => import(/* webpackChunkName: "panel-page-chunk" */'@/pages/panel/index.vue'),
    children: [
      {
        path: 'list_panel/:os_id',
        name: 'listPanel',
        component: () => import(/* webpackPrefetch: true */ /* webpackChunkName: "panel-page-chunk" */'@/pages/panel/list.vue'),
        props: route => ({
          osId: route.params.os_id,
        }),
        meta: {
          keepAlive: true,
        },
      },
      {
        path: 'panel-info',
        name: 'panel-info',
        component: () => import(/* webpackPrefetch: true */ /* webpackChunkName: "panel-page-chunk" */'@/pages/panel/info.vue'),
      },
    ],
  },
  {
    path: '/panel/:biz_id/chart_editor/:os_id/:chart_id?',
    name: 'chartEditor',
    component: () => import(/* webpackPrefetch: true */ /* webpackChunkName: "panel-page-chunk" */'@/pages/panel/chartEditor.vue'),
    meta: {
      keepAlive: false,
    },
    props: route => ({
      osId: route.params.os_id,
    }),
  },
];
Copy the code

BeforeRouteLeave, from. Meta. KeepAlive = false;

On the edit page, beforeRouteLeave is set to.meta.keepAlive = true;

This is actually a general scheme, such as “Understanding and Application of Keep-Alive cache”. Personally, I think this scheme is better. “Correct Use posture of Keep-Alive Cache of VUE component” is actually to set the weight of the path in the meta of the route. Such as level 1 page weight 100, level 2 page 1000, level 3 page 1000. According to the weight to do page caching and page switching animation slide direction.

Keep-alive Points to note summary

  • Matches the name field of the contained component first, or if name is not available, the registered name in the current component Components configuration.

  • Does not work properly in functional components ** because they do not cache instances **.

  • If the matching conditions exist in both include and exclude, exclude takes the highest priority (vue 2.4.2 version). For example, if the inclusion and exclusion matches component A, then component A will not be cached.

  • It is included in include, but complies with exclude and does not call activated or deactivated.

Reference article:

Vue learning hook – life cycle activated, deactivated www.cnblogs.com/mengtong/p/…

The Mounted function does not run in vue page rollback and how to resolve this problem www.cnblogs.com/candy-xia/p…

Vue-router keep-alive www.jb51.net/article/122…

Official: Component cache issue #811 github.com/vuejs/vue-r…

Vue keep-alive(1) : How does vue router ensure that the page does not refresh? Please indicate the source: www.zhoulujun.cn/html/webfro…