先前在 Day9 Vue指令- 條件渲染 內容中,有提到 v-if 可以依照條件判斷來決定內容是否呈現在畫面上,而今天的內容將介紹另外一種方法來實現動態控制元件的渲染~
透過使用 Vue 的 <component>
元素和特殊的屬性 is 來實現,其中 v-bind:is (簡寫為:is)傳入的值為被註冊的元件名或是導入的元件對象。
以下是官方文件的範例
<component :is="activeComponent" />
KeepAlive 是 Vue 提供的一個內置元件,使得元件經過切換後仍可以保留緩存其狀態,適合應用在分頁切換、表單輸入頁面。
將要緩存的動態元件寫在模板中的<keep-alive>
標籤裡。
以下是官方文件的範例
<!-- 非活躍的組件將會被緩存! -->
<KeepAlive>
<component :is="activeComponent" />
</KeepAlive>
由於 KeepAlive 元件預設會緩存內部所有元件實例,若緩存的元件數量過多,便可能會影響效能,因此透過以下這些 KeepAlive 的屬性,可以限制要緩存的元件。
以下是官方文件的範例
<KeepAlive include="a,b">
<component :is="view" />
</KeepAlive>
<KeepAlive exclude="c,d">
<component :is="view" />
</KeepAlive>
include 和 exclude 的 prop 值,除了以英文逗號分隔的字符串外,還可以是一個正則表達式,或是包含這兩種類型的一個數組。
以下是官方文件的範例
<!-- 正則表達式 (需使用 `v-bind`) -->
<KeepAlive :include="/a|b/">
<component :is="view" />
</KeepAlive>
<!-- 數組 (需使用 `v-bind`) -->
<KeepAlive :include="['a', 'b']">
<component :is="view" />
</KeepAlive>
<KeepAlive :max="8">
<component :is="activeComponent" />
</KeepAlive>
https://book.vue.tw/CH2/2-3-async-dynamic-components.html
https://zh-hk.vuejs.org/guide/essentials/component-basics.html#dynamic-components
https://hackmd.io/@ivaSrwTTSkC1jb66rpGfnQ/rJxzYnyB9