vue keep-alive組件的使用以及原理。

keep-alive

keep-alive是vue.js的內置組件,它可以把不活動的組件的實例保存在內存中,而不是直接的銷燬,它是一個抽象組件,不會被渲染到真實DOM中,也不會出如今父組件鏈中。
它提供了exclude和include兩個屬性,容許組件有條件的緩存。vue

使用

<keep-alive>
    <comment></comment>
</keep-alive>

上面的comment組件會被緩存起來。node

<keep-alive>
    <coma v-if="test"></coma>
    <comb v-else></comb>
</keep-alive>
<button @click="abc"></button>

export default{
    data(){
        reurn{
            test:true
        }
    },
    methods:{
        abc(){
            this.test=!this.test;
        }
    }
}

點擊button的時候coma組件和comb組件會發生切換,但這時候兩個組件的狀態會被緩存起來,假如說a和b組件中都有一個input標籤,這時切換input標籤的值不會改變。正則表達式

props

keep-alive組件提供了include和exclude兩個屬性來進行有條件的緩存,兩者均可以用逗號分隔字符串、正則表達式或則數組表示。數組

<keep-alive include="a">
    <component></component>
</keep-alive>
//name名爲a的組件會被緩存起來

<keep-alive exclude="a">
    <component></component>
</keep-alive>
//name名爲a的組件將不會被緩存。

生命鉤子

keep-alive提供了兩個生命鉤子,actived與deactived。
由於keep-alive會把組件保存到內存中,並不會銷燬或則從新構建,因此不會調用組件的creted等方法,須要使用actived和deactived兩個鉤子判斷組件是否處於活動狀態。緩存

深刻keep-alive組件的實現

created和destroyed鉤子
created鉤子會建立一個cache對象,用來做爲緩存容器,保存Vnode節點。函數

created{
    this.cache=Object.create(null);
}

destroyed鉤子則在組件銷燬的時候清除cache緩存中的全部組件實例。this

/* destroyed鉤子中銷燬全部cache中的組件實例 */
destroyed () {
    for (const key in this.cache) {
        pruneCacheEntry(this.cache[key])
    }
},

接下來是render函數。code

render () {
    /* 獲得slot插槽中的第一個組件 */
    const vnode: VNode = getFirstComponentChild(this.$slots.default)

    const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
    if (componentOptions) {
        // check pattern
        /* 獲取組件名稱,優先獲取組件的name字段,不然是組件的tag */
        const name: ?string = getComponentName(componentOptions)
        /* name不在inlcude中或者在exlude中則直接返回vnode(沒有取緩存) */
        if (name && (
        (this.include && !matches(this.include, name)) ||
        (this.exclude && matches(this.exclude, name))
        )) {
            return vnode
        }
        const key: ?string = vnode.key == null
        // same constructor may get registered as different local components
        // so cid alone is not enough (#3269)
        ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
        : vnode.key
        /* 若是已經作過緩存了則直接從緩存中獲取組件實例給vnode,還未緩存過則進行緩存 */
        if (this.cache[key]) {
            vnode.componentInstance = this.cache[key].componentInstance
        } else {
            this.cache[key] = vnode
        }
        /* keepAlive標記位 */
        vnode.data.keepAlive = true
    }
    return vnode
}

首先經過getFirstComponentChild獲取第一個子組件,獲取該組件的name(存在組件名則直接使用組件名,不然會使用tag)。接下來會將這個name經過include與exclude屬性進行匹配,匹配不成功(說明不須要進行緩存)則不進行任何操做直接返回vnode。component

/* 檢測name是否匹配 */
function matches (pattern: string | RegExp, name: string): boolean {
  if (typeof pattern === 'string') {
    /* 字符串狀況,如a,b,c */
    return pattern.split(',').indexOf(name) > -1
  } else if (isRegExp(pattern)) {
    /* 正則 */
    return pattern.test(name)
  }
  /* istanbul ignore next */
  return false
}

檢測include與exclude屬性匹配的函數很簡單,include與exclude屬性支持字符串如"a,b,c"這樣組件名以逗號隔開的狀況以及正則表達式。matches經過這兩種方式分別檢測是否匹配當前組件。對象

if (this.cache[key]) {
    vnode.componentInstance = this.cache[key].componentInstance
} else {
    this.cache[key] = vnode
}

接下來的事情很簡單,根據key在this.cache中查找,若是存在則說明以前已經緩存過了,直接將緩存的vnode的componentInstance(組件實例)覆蓋到目前的vnode上面。不然將vnode存儲在cache中。
最後返回vnode(有緩存時該vnode的componentInstance已經被替換成緩存中的了)。
用watch來監聽pruneCache與pruneCache這兩個屬性的改變,在改變的時候修改cache緩存中的緩存數據。

watch: {
    /* 監視include以及exclude,在被修改的時候對cache進行修正 */
    include (val: string | RegExp) {
        pruneCache(this.cache, this._vnode, name => matches(val, name))
    },
    exclude (val: string | RegExp) {
        pruneCache(this.cache, this._vnode, name => !matches(val, name))
    }
},

來看一下pruneCache的實現。

/* 修正cache */
function pruneCache (cache: VNodeCache, current: VNode, filter: Function) {
  for (const key in cache) {
    /* 取出cache中的vnode */
    const cachedNode: ?VNode = cache[key]
    if (cachedNode) {
      const name: ?string = getComponentName(cachedNode.componentOptions)
      /* name不符合filter條件的,同時不是目前渲染的vnode時,銷燬vnode對應的組件實例(Vue實例),並從cache中移除 */
      if (name && !filter(name)) {
        if (cachedNode !== current) {
          pruneCacheEntry(cachedNode)
        }
        cache[key] = null
      }
    }
  }
} 

/* 銷燬vnode對應的組件實例(Vue實例) */
function pruneCacheEntry (vnode: ?VNode) {
  if (vnode) {
    vnode.componentInstance.$destroy()
  }
}
遍歷cache中的全部項,若是不符合filter指定的規則的話,則會執行pruneCacheEntry。pruneCacheEntry則會調用組件實例的$destroy方法來將組件銷燬。
相關文章
相關標籤/搜索