回首Vue3之組件篇(三)

這是我參與8月更文挑戰的第12天,活動詳情查看:8月更文挑戰html

這篇文章咱們來說一下內置組件keep-aliveslot的使用方法,在使用它們的時候咱們又該注意什麼呢,下面讓咱們一探究竟把。正則表達式

keep-alive

官方說,<keep-alive> 包裹動態組件時,會緩存不活動的組件實例,而不是銷燬它們。和 <transition> 類似,<keep-alive> 是一個抽象組件:它自身不會渲染一個 DOM 元素,也不會出如今組件的父組件鏈中。數組

其實,就是來作組件緩存的,這是由於咱們的實際需求中會有這樣的狀況:當切換到已顯示過的組件的時候,咱們不但願這個組件從新渲染,就可使用<keep-alive>緩存

如何使用

基本使用markdown

<keep-alive>能夠結合<component>使用,以下:app

<keep-alive>
  <component :is="view"></component>
</keep-alive>
複製代碼

條件判斷 <keep-alive>能夠結合v-ifv-else-ifv-else使用。post

<keep-alive>
  <comp-a v-if="a > 1"></comp-a>
  <comp-b v-else></comp-b>
</keep-alive>
複製代碼

結合過渡或動畫效果使用動畫

<keep-alive>能夠結合<transition>使用,以下:ui

<transition>
  <keep-alive>
    <component :is="view"></component>
  </keep-alive>
</transition>
複製代碼

當咱們須要頻繁的切換組件,並且須要帶有過渡或動畫效果的時候,可使用這種方式。值得咱們注意的是:<keep-alive> 是用在其一個直屬的子組件被切換的情形。若是你在其中有 v-for 則不會工做。若是有上述的多個條件性的子元素,<keep-alive> 要求同時只有一個子元素被渲染。url

keep-alive 的 Props

include 和 exclude

include 和 exclude prop 容許組件有條件地緩存。include表示包含, exclude表示排除。兩者均可以用逗號分隔字符串、正則表達式或一個數組來表示。

  1. 逗號分隔字符串
<keep-alive include="a,b">
  <component :is="view"></component>
</keep-alive>
複製代碼
  1. 正則表達式,須要使用v-bind
<keep-alive :include="/a|b/">
  <component :is="view"></component>
</keep-alive>
複製代碼
  1. 一個數組,須要使用v-bind
<keep-alive :include="['a', 'b']">
  <component :is="view"></component>
</keep-alive>
複製代碼

exclude也是一樣的用法,優先匹配組件的name,若是 name 選項不可用,則匹配它的局部註冊名稱 (父組件 components 選項的鍵值)。

max

最多緩存組件數量,若是超過這個數量,那麼最久沒被訪問的會被銷燬。使用以下:

<keep-alive :max="10">
  <component :is="view"></component>
</keep-alive>
複製代碼

slot

<slot> 元素做爲組件模板之中的內容分發插槽,<slot> 元素自身將被替換。在回首Vue3之指令篇(八)這篇文章中,咱們在講v-slot的同時,也詳細講了slot的用法,傳送門過去能夠詳細的瞭解一下。

總結

  1. <keep-alive>可使用include 和 exclude按需緩存。

  2. slot的具名插槽和做用域插槽要合理的去使用。

相關文章
相關標籤/搜索