跳轉到內容

KeepAlive

<KeepAlive> 是一個內建元件,允許我們在動態地在多個元件之間切換時有條件地快取元件例項。

基本用法

在元件基礎章節中,我們介紹了使用 <component> 特殊元素實現的 動態元件 的語法

模板
<component :is="activeComponent" />

預設情況下,當從活動元件例項切換離開時,該例項將被解除安裝。這會導致它持有的任何更改後的狀態丟失。當該元件再次顯示時,將建立一個新的例項,僅包含初始狀態。

在下面的示例中,我們有兩個有狀態的元件 - A 包含一個計數器,而 B 包含一個透過 v-model 與輸入同步的訊息。嘗試更新其中一個元件的狀態,切換離開,然後切換回它

當前元件:A

計數:0

你會注意到,當切換回時,之前更改後的狀態已經被重置。

在切換時建立新的元件例項通常是正常的行為,但在這個情況下,我們確實希望兩個元件例項在它們不活躍時也能被保留。為了解決這個問題,我們可以用 <KeepAlive> 內建元件包裹我們的動態元件

模板
<!-- Inactive components will be cached! -->
<KeepAlive>
  <component :is="activeComponent" />
</KeepAlive>

現在,狀態將在元件切換之間保持持久

當前元件:A

計數:0

提示

當在 DOM 模板中 使用時,應將其引用為 <keep-alive>

包含/排除

預設情況下,<KeepAlive> 將快取任何包含在其內的元件例項。我們可以透過 includeexclude 屬性自定義此行為。這兩個屬性可以是逗號分隔的字串、一個 RegExp 或一個包含型別的陣列

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

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

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

匹配是針對元件的 name 選項進行的,因此需要由 KeepAlive 條件快取元件必須顯式宣告一個 name 選項。

提示

從版本 3.2.34 開始,使用 <script setup> 的單檔案元件將自動根據檔名推斷其 name 選項,從而無需手動宣告名稱。

最大快取的例項數

我們可以透過 max 屬性限制可以快取的元件例項的最大數量。當指定了 max 時,<KeepAlive> 的行為類似於一個 LRU 快取:如果快取的例項數量即將超過指定的最大計數,則將銷燬最近最少訪問的快取例項,為新例項騰出空間。

模板
<KeepAlive :max="10">
  <component :is="activeComponent" />
</KeepAlive>

快取的例項的生命週期

當一個元件例項從DOM中移除,但它是被<KeepAlive>快取的元件樹的一部分時,它會進入一個非啟用狀態,而不是被解除安裝。當一個元件例項作為快取的樹的組成部分被插入到DOM中時,它會被啟用

可以透過使用onActivated()onDeactivated()來為這兩個狀態註冊生命週期鉤子。

vue
<script setup>
import { onActivated, onDeactivated } from 'vue'

onActivated(() => {
  // called on initial mount
  // and every time it is re-inserted from the cache
})

onDeactivated(() => {
  // called when removed from the DOM into the cache
  // and also when unmounted
})
</script>

可以透過使用activateddeactivated鉤子來為這兩個狀態註冊生命週期鉤子。

js
export default {
  activated() {
    // called on initial mount
    // and every time it is re-inserted from the cache
  },
  deactivated() {
    // called when removed from the DOM into the cache
    // and also when unmounted
  }
}

注意,

  • onActivatedactivated在掛載時也會被呼叫,而onDeactivateddeactivated在解除安裝時會被呼叫。

  • 這兩個鉤子不僅適用於由<KeepAlive>快取的根元件,也適用於快取的樹中的後代元件。


相關

KeepAlive已載入