当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Vue.js <KeepAlive>用法及代码示例


缓存包在里面的动态切换组件。

属性

interface KeepAliveProps {
  /**
   * If specified, only components with names matched by
   * `include` will be cached.
   */
  include?: MatchPattern
  /**
   * Any component with a name matched by `exclude` will
   * not be cached.
   */
  exclude?: MatchPattern
  /**
   * The maximum number of component instances to cache.
   */
  max?: number | string
}

type MatchPattern = string | RegExp | (string | RegExp)[]

细节

当包在动态组件上时,<KeepAlive> 缓存非活动组件实例而不破坏它们。

任何时候都只能有一个活动组件实例作为<KeepAlive> 的直接子代。

当一个组件在 <KeepAlive> 中被切换时,它的 activateddeactivated 生命周期钩子将被相应地调用,提供了 mountedunmounted 的替代方案,它们没有被调用。这适用于<KeepAlive> 的直接子代及其所有后代。

示例

基本用法:

<KeepAlive>
  <component :is="view"></component>
</KeepAlive>

当与v-if /v-else 分支一起使用时,一次只能渲染一个组件:

<KeepAlive>
  <comp-a v-if="a > 1"></comp-a>
  <comp-b v-else></comp-b>
</KeepAlive>

<Transition> 一起使用:

<Transition>
  <KeepAlive>
    <component :is="view"></component>
  </KeepAlive>
</Transition>

使用 include /exclude

<!-- comma-delimited string -->
<KeepAlive include="a,b">
  <component :is="view"></component>
</KeepAlive>

<!-- regex (use `v-bind`) -->
<KeepAlive :include="/a|b/">
  <component :is="view"></component>
</KeepAlive>

<!-- Array (use `v-bind`) -->
<KeepAlive :include="['a', 'b']">
  <component :is="view"></component>
</KeepAlive>

max 的用法:

<KeepAlive :max="10">
  <component :is="view"></component>
</KeepAlive>

相关用法


注:本文由纯净天空筛选整理自vuejs.org大神的英文原创作品 <KeepAlive>。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。