usage


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, nor does it appear in the component’s parent chain. When a component is toggled within

, its Mounted and unmounted lifecycle hooks are not called, but activated and deactivated instead.


use

  • Configure whether components need to be cached in the routing component configuration filemetaattribute
{ 
  path: '/dynamic'.name: 'Dynamic'.component: () = > import('@/views/Dynamic.vue'), 
  meta: { 
    keepAlive: true.showFooter: true,}},Copy the code
  • In the root componentApp.vueThe use ofkeep-aliveThe tag contains the components to be cached
<! -- this is vue3, different from vue2, if you use vue2. X, there will be a warning --><router-view v-slot="{ Component }">
  <keep-alive>
    <component :is="Component" :key="$route.name" v-if="$route.meta.keepAlive" />
  </keep-alive>
  <component :is="Component" :key="$route.name" v-if=! "" $route.meta.keepAlive" />
</router-view>
Copy the code
  • Caching page usage
onActivated(() = > { // Triggered when the wrapped component is active
      // Logical code
 }
onDeactivated(() = > { // Emitted when the wrapped component stops being used
    // Logical code
})
Copy the code

Pay attention to

  • The first time a page is displayed, the hook sequence is created-> Mounted ->activated, so do not write the same logic in mounted and activated

  • Multi-page caching requires a key attribute to indicate component uniqueness and mapping, for example :key="$route.path"

  • KeepAlive: keepAlive: keepAlive: keepAlive: keepAlive: keepAlive: keepAlive: keepAlive: keepAlive: keepAlive: keepAlive: keepAlive: keepAlive: keepAlive: keepAlive: keepAlive Rendering a component that does not use Keep-alive triggers the corresponding code