當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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>。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。