vue動態組件和 keep-alive


所謂動態組件就是讓多個組件使用同一個掛載點,並動態切換。

is 用法

通過使用保留的 <component></component> 元素,動態地綁定到它的 is 特性,我們讓多個組件可以使用同一個掛載點,並動態切換。根據 v-bind:is="組件名" ,組件名就會自動去匹配對應的組件,如果匹配不到,則不顯示。改變掛載的組件,只需要修改 is 屬性的值即可。

demo

<!DOCTYPE html>
<html>
<head>
  <title>動態組件demo</title>
  <script src="https://unpkg.com/vue"></script>
</head>
<body>
  <div id="example">
    <span @click="index = 0">主頁</span>
    <span @click="index = 1">詳情頁</span>
    <span @click="index = 2">存檔頁</span>
    <component :is="currentView"></component>
  </div>
  <script>
    const home = {
      template: '<div>我是主頁</div>'
    };
    const detail = {
      template: '<div>我是詳情頁</div>'
    };
    const archive = {
      template: '<div>我是存檔頁</div>'
    };
    new Vue({
      el: '#example',
      components: {
        home,
        detail,
        archive,
      },
      data: {
        index: 0,
        arr: ['home', 'detail', 'archive'],
      },
      computed: {
        currentView() {
          return this.arr[this.index];
        }
      }
    })
  </script>
</body>
</html>

keep-alive 組件

上面我們已經通過綁定 is 屬性來切換不同的組件,被切換掉的組件(非當前顯示組件),是被直接移除了。用 <keep-alive></keep-alive> 包裹組件,可以使被切換掉的組件保留在內存中,從而保留它的狀態避免切換顯示的時候重新渲染,能夠提高性能。

keep-alive 是一個抽象組件,它本身不會被渲染為一個DOM元素,也不會出現在父組件鏈中。當 keep-alive 包裹組件時,會緩存不活動的組件實例,而不是直接銷毀

基礎用法示例:

 <div id="example">
    <button @click="change">切換頁面</button>
    <keep-alive>
      <component :is="currentView"></component>
    </keep-alive>
  </div>

activated 和 deactivated

在 2.2.0 及其更高版本中,activated 和 deactivated 將會在 <keep-alive> 樹內的所有嵌套組件中觸發。

當組件在 <keep-alive> 內被切換,它的 activateddeactivated 這兩個生命周期鈎子函數將會被對應執行。

props

  • include 字符串或者正則表達式,只有名稱匹配的組件會被緩存
  • exclude 字符串或者正則表達式,任何名稱匹配的組件都不會被緩存
  • max 數字,最多可以緩存多少組件實例

匹配首先檢查組件自身的 name 選項,如果 name 選項不可用,則匹配它的局部注冊名稱 (父組件 components 選項的鍵值)。匿名組件不能被匹配。

<!-- 逗號分隔字符串 -->
<keep-alive include="a,b">
  <component :is="view"></component>
</keep-alive>
 
<!-- 正則表達式 (使用 `v-bind`) -->
<keep-alive :include="/a|b/">
  <component :is="view"></component>
</keep-alive>
 
<!-- 數組 (使用 `v-bind`) -->
<keep-alive :include="['a', 'b']">
  <component :is="view"></component>
</keep-alive>

max 最多可以緩存多少組件實例。一旦這個數字達到了,在新實例被創建之前,已緩存組件中最久沒有被訪問的實例會被銷毀掉。

<keep-alive :max="10">
  <component :is="view"></component>
</keep-alive>

注意

不會在函數式組件中正常工作,因為它們沒有緩存實例。

本文轉自:https://blog.csdn.net/z591102/article/details/107380262


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM