1. 程式人生 > >聊聊keep-alive組件的使用及其實現原理

聊聊keep-alive組件的使用及其實現原理

white pes input clas cto lods num mco tumx

寫在前面

因為對Vue.js很感興趣,而且平時工作的技術棧也是Vue.js,這幾個月花了些時間研究學習了一下Vue.js源碼,並做了總結與輸出。

文章的原地址:https://github.com/answershuto/learnVue。

在學習過程中,為Vue加上了中文的註釋https://github.com/answershuto/learnVue/tree/master/vue-src以及Vuex的註釋https://github.com/answershuto/learnVue/tree/master/vuex-src,希望可以對其他想學習源碼的小夥伴有所幫助。

可能會有理解存在偏差的地方,歡迎提issue指出,共同學習,共同進步。

keep-alive

keep-alive是Vue.js的一個內置組件。它能夠不活動的組件實例保存在內存中,而不是直接將其銷毀,它是一個抽象組件,不會被渲染到真實DOM中,也不會出現在父組件鏈中。

它提供了include與exclude兩個屬性,允許組件有條件地進行緩存。

具體內容可以參考官網。

使用

用法

<keep-alive>
    <component></component>
</keep-alive>

這裏的component組件會被緩存起來。

舉個栗子

<keep-alive>
    <coma v-if="test"
>
</coma> <comb v-else="test"></comb> </keep-alive> <button @click="test=handleClick">請點擊</button>
export default {
    data () {
        return {
            test: true
        }
    },
    methods: {
        handleClick () {
            this.test = !this.test;
        }
    }
}

在點擊button時候,coma與comb兩個組件會發生切換,但是這時候這兩個組件的狀態會被緩存起來,比如說coma與comb組件中都有一個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提供了兩個生命鉤子,分別是activated與deactivated。

因為keep-alive會將組件保存在內存中,並不會銷毀以及重新創建,所以不會重新調用組件的created等方法,需要用activated與deactivated這兩個生命鉤子來得知當前組件是否處於活動狀態。


深入keep-alive組件實現

說完了keep-alive組件的使用,我們從源碼角度看一下keep-alive組件究竟是如何實現組件的緩存的呢?

created與destroyed鉤子

created鉤子會創建一個cache對象,用來作為緩存容器,保存vnode節點。

created () {
    /* 緩存對象 */
    this.cache = Object.create(null)
},

destroyed鉤子則在組件被銷毀的時候清除cache緩存中的所有組件實例。

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

render

接下來是render函數。

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,vnode是一個VNode類型的對象,不了解VNode的同學可以參考筆者的另一篇文章《VNode節點》 .

/* 檢測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

用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方法來將組件銷毀。

最後

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

關於

作者:染陌

Email:[email protected] or [email protected]

Github: https://github.com/answershuto

知乎:https://www.zhihu.com/people/cao-yang-49/activities

轉載請註明出處,謝謝。

歡迎關註我的公眾號

技術分享

?

聊聊keep-alive組件的使用及其實現原理