1. 程式人生 > >vue keep-alive元件使用

vue keep-alive元件使用

keep-alive是Vue.js的一個內建元件。<keep-alive> 包裹動態元件時,會快取不活動的元件例項,而不是銷燬它們。它自身不會渲染一個 DOM 元素,也不會出現在父元件鏈中。 當元件在 <keep-alive> 內被切換,它的 activated 和 deactivated 這兩個生命週期鉤子函式將會被對應執行。它提供了include與exclude兩個屬性,允許元件有條件地進行快取。

舉個栗子

 
  1. <keep-alive>

  2. <router-view v-if="$route.meta.keepAlive"></router-view>

  3. </keep-alive>

  4. <router-view v-if="!$route.meta.keepAlive"></router-view>

  5. 複製程式碼


切換按鈕

在點選button時候,兩個input會發生切換,但是這時候這兩個輸入框的狀態會被快取起來,input標籤中的內容不會因為元件的切換而消失。

 
  1. * include - 字串或正則表示式。只有匹配的元件會被快取。

  2. * exclude - 字串或正則表示式。任何匹配的元件都不會被快取。

  3. 複製程式碼

 
  1. <keep-alive include="a">

  2. <component></component>

  3. </keep-alive>

  4. 複製程式碼

只快取元件別民name為a的元件

 
  1. <keep-alive exclude="a">

  2. <component></component>

  3. </keep-alive>

  4. 複製程式碼

除了name為a的元件,其他都快取下來

生命週期鉤子

生命鉤子keep-alive提供了兩個生命鉤子,分別是activated與deactivated。

因為keep-alive會將元件儲存在記憶體中,並不會銷燬以及重新建立,所以不會重新呼叫元件的created等方法,需要用activated與deactivated這兩個生命鉤子來得知當前元件是否處於活動狀態。

深入keep-alive元件實現

 

檢視vue--keep-alive元件原始碼可以得到以下資訊

 

created鉤子會建立一個cache物件,用來作為快取容器,儲存vnode節點。

 
  1.  
  2. props: {

  3. include: patternTypes,

  4. exclude: patternTypes,

  5. max: [String, Number]

  6. },

  7.  
  8. created () {

  9. // 建立快取物件

  10. this.cache = Object.create(null)

  11. // 建立一個key別名陣列(元件name)

  12. this.keys = []

  13. },

  14. 複製程式碼

destroyed鉤子則在元件被銷燬的時候清除cache快取中的所有元件例項。

 
  1. destroyed () {

  2. /* 遍歷銷燬所有快取的元件例項*/

  3. for (const key in this.cache) {

  4. pruneCacheEntry(this.cache, key, this.keys)

  5. }

  6. },

  7. 複製程式碼

:::demo

 
  1. render () {

  2. /* 獲取插槽 */

  3. const slot = this.$slots.default

  4. /* 根據插槽獲取第一個元件元件 */

  5. const vnode: VNode = getFirstComponentChild(slot)

  6. const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions

  7. if (componentOptions) {

  8. // 獲取元件的名稱(是否設定了元件名稱name,沒有則返回元件標籤名稱)

  9. const name: ?string = getComponentName(componentOptions)

  10. // 解構物件賦值常量

  11. const { include, exclude } = this

  12. if ( /* name不在inlcude中或者在exlude中則直接返回vnode */

  13. // not included

  14. (include && (!name || !matches(include, name))) ||

  15. // excluded

  16. (exclude && name && matches(exclude, name))

  17. ) {

  18. return vnode

  19. }

  20.  
  21. const { cache, keys } = this

  22. const key: ?string = vnode.key == null

  23. // same constructor may get registered as different local components

  24. // so cid alone is not enough (#3269)

  25. ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')

  26. : vnode.key

  27. if (cache[key]) { // 判斷當前是否有快取,有則取快取的例項,無則進行快取

  28. vnode.componentInstance = cache[key].componentInstance

  29. // make current key freshest

  30. remove(keys, key)

  31. keys.push(key)

  32. } else {

  33. cache[key] = vnode

  34. keys.push(key)

  35. // 判斷是否設定了最大快取例項數量,超過則刪除最老的資料,

  36. if (this.max && keys.length > parseInt(this.max)) {

  37. pruneCacheEntry(cache, keys[0], keys, this._vnode)

  38. }

  39. }

  40. // 給vnode打上快取標記

  41. vnode.data.keepAlive = true

  42. }

  43. return vnode || (slot && slot[0])

  44. }

  45.  
  46. // 銷燬例項

  47. function pruneCacheEntry (

  48. cache: VNodeCache,

  49. key: string,

  50. keys: Array<string>,

  51. current?: VNode

  52. ) {

  53. const cached = cache[key]

  54. if (cached && (!current || cached.tag !== current.tag)) {

  55. cached.componentInstance.$destroy()

  56. }

  57. cache[key] = null

  58. remove(keys, key)

  59. }

  60.  
  61.  
  62. // 快取

  63. function pruneCache (keepAliveInstance: any, filter: Function) {

  64. const { cache, keys, _vnode } = keepAliveInstance

  65. for (const key in cache) {

  66. const cachedNode: ?VNode = cache[key]

  67. if (cachedNode) {

  68. const name: ?string = getComponentName(cachedNode.componentOptions)

  69. // 元件name 不符合filler條件, 銷燬例項,移除cahe

  70. if (name && !filter(name)) {

  71. pruneCacheEntry(cache, key, keys, _vnode)

  72. }

  73. }

  74. }

  75. }

  76.  
  77. // 篩選過濾函式

  78. function matches (pattern: string | RegExp | Array<string>, name: string): boolean {

  79. if (Array.isArray(pattern)) {

  80. return pattern.indexOf(name) > -1

  81. } else if (typeof pattern === 'string') {

  82. return pattern.split(',').indexOf(name) > -1

  83. } else if (isRegExp(pattern)) {

  84. return pattern.test(name)

  85. }

  86. /* istanbul ignore next */

  87. return false

  88. }

  89.  
  90.  
  91. // 檢測 include 和 exclude 資料的變化,實時寫入讀取快取或者刪除

  92. mounted () {

  93. this.$watch('include', val => {

  94. pruneCache(this, name => matches(val, name))

  95. })

  96. this.$watch('exclude', val => {

  97. pruneCache(this, name => !matches(val, name))

  98. })

  99. },

  100.  
  101. 複製程式碼

:::

通過檢視Vue原始碼可以看出,keep-alive預設傳遞3個屬性,include 、exclude、max, max 最大可快取的長度

結合原始碼我們可以實現一個可配置快取的router-view

 
  1. <!--exclude - 字串或正則表示式。任何匹配的元件都不會被快取。-->

  2. <!--TODO 匹配首先檢查元件自身的 name 選項,如果 name 選項不可用,則匹配它的區域性註冊名稱-->

  3. <keep-alive :exclude="keepAliveConf.value">

  4. <router-view class="child-view" :key="$route.fullPath"></router-view>

  5. </keep-alive>

  6. <!-- 或者 -->

  7. <keep-alive :include="keepAliveConf.value">

  8. <router-view class="child-view" :key="$route.fullPath"></router-view>

  9. </keep-alive>

  10. <!-- 具體使用 include 還是exclude 根據專案是否需要快取的頁面數量多少來決定-->

  11. 複製程式碼

建立一個keepAliveConf.js 放置需要匹配的元件名

 
  1. // 路由元件命名集合

  2. var arr = ['component1', 'component2'];

  3. export default {value: routeList.join()};

  4. 複製程式碼

配置重置快取的全域性方法

 
  1. import keepAliveConf from 'keepAliveConf.js'

  2. Vue.mixin({

  3. methods: {

  4. // 傳入需要重置的元件名字

  5. resetKeepAive(name) {

  6. const conf = keepAliveConf.value;

  7. let arr = keepAliveConf.value.split(',');

  8. if (name && typeof name === 'string') {

  9. let i = arr.indexOf(name);

  10. if (i > -1) {

  11. arr.splice(i, 1);

  12. keepAliveConf.value = arr.join();

  13. setTimeout(() => {

  14. keepAliveConf.value = conf

  15. }, 500);

  16. }

  17. }

  18. },

  19. }

  20. })

  21. 複製程式碼

在合適的時機呼叫呼叫this.resetKeepAive(name),觸發keep-alive銷燬元件例項;

 

Vue.js內部將DOM節點抽象成了一個個的VNode節點,keep-alive元件的快取也是基於VNode節點的而不是直接儲存DOM結構。它將滿足條件的元件在cache物件中快取起來,在需要重新渲染的時候再將vnode節點從cache物件中取出並渲染。


作者:walker-design
連結:https://juejin.im/post/5b4320f9f265da0f7f4488f6
來源:掘金
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。

轉載於:https://blog.csdn.net/sinat_17775997/article/details/80993644