新聞中心
這篇文章主要講解了“vue內(nèi)置組件keep-alive怎么使用”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“vue內(nèi)置組件keep-alive怎么使用”吧!
創(chuàng)新互聯(lián)建站成立10年來,這條路我們正越走越好,積累了技術(shù)與客戶資源,形成了良好的口碑。為客戶提供網(wǎng)站設(shè)計(jì)、做網(wǎng)站、網(wǎng)站策劃、網(wǎng)頁(yè)設(shè)計(jì)、域名注冊(cè)、網(wǎng)絡(luò)營(yíng)銷、VI設(shè)計(jì)、網(wǎng)站改版、漏洞修補(bǔ)等服務(wù)。網(wǎng)站是否美觀、功能強(qiáng)大、用戶體驗(yàn)好、性價(jià)比高、打開快等等,這些對(duì)于網(wǎng)站建設(shè)都非常重要,創(chuàng)新互聯(lián)建站通過對(duì)建站技術(shù)性的掌握、對(duì)創(chuàng)意設(shè)計(jì)的研究為客戶提供一站式互聯(lián)網(wǎng)解決方案,攜手廣大客戶,共同發(fā)展進(jìn)步。
一、Keep-alive 是什么
keep-alive
是vue
中的內(nèi)置組件,能在組件切換過程中將狀態(tài)保留在內(nèi)存中,防止重復(fù)渲染DOM
。
keep-alive
包裹動(dòng)態(tài)組件時(shí),會(huì)緩存不活動(dòng)的組件實(shí)例,而不是銷毀它們。
keep-alive
可以設(shè)置以下props
屬性:
include
- 字符串或正則表達(dá)式。只有名稱匹配的組件會(huì)被緩存exclude
- 字符串或正則表達(dá)式。任何名稱匹配的組件都不會(huì)被緩存max
- 數(shù)字。最多可以緩存多少組件實(shí)例
關(guān)于keep-alive
的基本用法:
使用includes
和exclude
:
匹配首先檢查組件自身的 name
選項(xiàng),如果 name
選項(xiàng)不可用,則匹配它的局部注冊(cè)名稱 (父組件 components
選項(xiàng)的鍵值),匿名組件不能被匹配
設(shè)置了 keep-alive 緩存的組件,會(huì)多出兩個(gè)生命周期鉤子(activated
與deactivated
):
首次進(jìn)入組件時(shí):
beforeRouteEnter
>beforeCreate
>created
>mounted
>activated
> ... ... >beforeRouteLeave
>deactivated
再次進(jìn)入組件時(shí):
beforeRouteEnter
>activated
> ... ... >beforeRouteLeave
>deactivated
二、使用場(chǎng)景
使用原則:當(dāng)我們?cè)谀承﹫?chǎng)景下不需要讓頁(yè)面重新加載時(shí)我們可以使用keepalive
舉個(gè)栗子:
當(dāng)我們從首頁(yè)
–>列表頁(yè)
–>商詳頁(yè)
–>再返回
,這時(shí)候列表頁(yè)應(yīng)該是需要keep-alive
從首頁(yè)
–>列表頁(yè)
–>商詳頁(yè)
–>返回到列表頁(yè)(需要緩存)
–>返回到首頁(yè)(需要緩存)
–>再次進(jìn)入列表頁(yè)(不需要緩存)
,這時(shí)候可以按需來控制頁(yè)面的keep-alive
在路由中設(shè)置keepAlive
屬性判斷是否需要緩存
{
path: 'list',
name: 'itemList', // 列表頁(yè)
component (resolve) {
require(['@/pages/item/list'], resolve)
},
meta: {
keepAlive: true,
title: '列表頁(yè)'
}
}
使用
三、原理分析
keep-alive
是vue
中內(nèi)置的一個(gè)組件
源碼位置:src/core/components/keep-alive.js
export default {
name: 'keep-alive',
abstract: true,
props: {
include: [String, RegExp, Array],
exclude: [String, RegExp, Array],
max: [String, Number]
},
created () {
this.cache = Object.create(null)
this.keys = []
},
destroyed () {
for (const key in this.cache) {
pruneCacheEntry(this.cache, key, this.keys)
}
},
mounted () {
this.$watch('include', val => {
pruneCache(this, name => matches(val, name))
})
this.$watch('exclude', val => {
pruneCache(this, name => !matches(val, name))
})
},
render() {
/* 獲取默認(rèn)插槽中的第一個(gè)組件節(jié)點(diǎn) */
const slot = this.$slots.default
const vnode = getFirstComponentChild(slot)
/* 獲取該組件節(jié)點(diǎn)的componentOptions */
const componentOptions = vnode && vnode.componentOptions
if (componentOptions) {
/* 獲取該組件節(jié)點(diǎn)的名稱,優(yōu)先獲取組件的name字段,如果name不存在則獲取組件的tag */
const name = getComponentName(componentOptions)
const { include, exclude } = this
/* 如果name不在inlcude中或者存在于exlude中則表示不緩存,直接返回vnode */
if (
(include && (!name || !matches(include, name))) ||
// excluded
(exclude && name && matches(exclude, name))
) {
return vnode
}
const { cache, keys } = this
/* 獲取組件的key值 */
const key = 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
/* 拿到key值后去this.cache對(duì)象中去尋找是否有該值,如果有則表示該組件有緩存,即命中緩存 */
if (cache[key]) {
vnode.componentInstance = cache[key].componentInstance
// make current key freshest
remove(keys, key)
keys.push(key)
}
/* 如果沒有命中緩存,則將其設(shè)置進(jìn)緩存 */
else {
cache[key] = vnode
keys.push(key)
// prune oldest entry
/* 如果配置了max并且緩存的長(zhǎng)度超過了this.max,則從緩存中刪除第一個(gè) */
if (this.max && keys.length > parseInt(this.max)) {
pruneCacheEntry(cache, keys[0], keys, this._vnode)
}
}
vnode.data.keepAlive = true
}
return vnode || (slot && slot[0])
}
}
可以看到該組件沒有template
,而是用了render
,在組件渲染的時(shí)候會(huì)自動(dòng)執(zhí)行render
函數(shù)
this.cache
是一個(gè)對(duì)象,用來存儲(chǔ)需要緩存的組件,它將以如下形式存儲(chǔ):
this.cache = {
'key1':'組件1',
'key2':'組件2',
// ...
}
在組件銷毀的時(shí)候執(zhí)行pruneCacheEntry
函數(shù)
function pruneCacheEntry (
cache: VNodeCache,
key: string,
keys: Array
在mounted
鉤子函數(shù)中觀測(cè) include
和 exclude
的變化,如下:
mounted () {
this.$watch('include', val => {
pruneCache(this, name => matches(val, name))
})
this.$watch('exclude', val => {
pruneCache(this, name => !matches(val, name))
})
}
如果include
或exclude
發(fā)生了變化,即表示定義需要緩存的組件的規(guī)則或者不需要緩存的組件的規(guī)則發(fā)生了變化,那么就執(zhí)行pruneCache
函數(shù),函數(shù)如下:
function pruneCache (keepAliveInstance, filter) {
const { cache, keys, _vnode } = keepAliveInstance
for (const key in cache) {
const cachedNode = cache[key]
if (cachedNode) {
const name = getComponentName(cachedNode.componentOptions)
if (name && !filter(name)) {
pruneCacheEntry(cache, key, keys, _vnode)
}
}
}
}
在該函數(shù)內(nèi)對(duì)this.cache
對(duì)象進(jìn)行遍歷,取出每一項(xiàng)的name
值,用其與新的緩存規(guī)則進(jìn)行匹配,如果匹配不上,則表示在新的緩存規(guī)則下該組件已經(jīng)不需要被緩存,則調(diào)用pruneCacheEntry
函數(shù)將其從this.cache
對(duì)象剔除即可
關(guān)于keep-alive
的最強(qiáng)大緩存功能是在render
函數(shù)中實(shí)現(xiàn)
首先獲取組件的key
值:
const key = vnode.key == null?
componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
: vnode.key
拿到key
值后去this.cache
對(duì)象中去尋找是否有該值,如果有則表示該組件有緩存,即命中緩存,如下:
/* 如果命中緩存,則直接從緩存中拿 vnode 的組件實(shí)例 */
if (cache[key]) {
vnode.componentInstance = cache[key].componentInstance
/* 調(diào)整該組件key的順序,將其從原來的地方刪掉并重新放在最后一個(gè) */
remove(keys, key)
keys.push(key)
}
直接從緩存中拿 vnode
的組件實(shí)例,此時(shí)重新調(diào)整該組件key
的順序,將其從原來的地方刪掉并重新放在this.keys
中最后一個(gè)
this.cache
對(duì)象中沒有該key
值的情況,如下:
/* 如果沒有命中緩存,則將其設(shè)置進(jìn)緩存 */
else {
cache[key] = vnode
keys.push(key)
/* 如果配置了max并且緩存的長(zhǎng)度超過了this.max,則從緩存中刪除第一個(gè) */
if (this.max && keys.length > parseInt(this.max)) {
pruneCacheEntry(cache, keys[0], keys, this._vnode)
}
}
表明該組件還沒有被緩存過,則以該組件的key
為鍵,組件vnode
為值,將其存入this.cache
中,并且把key
存入this.keys
中
此時(shí)再判斷this.keys
中緩存組件的數(shù)量是否超過了設(shè)置的最大緩存數(shù)量值this.max
,如果超過了,則把第一個(gè)緩存組件刪掉
四、思考題:緩存后如何獲取數(shù)據(jù)
解決方案可以有以下兩種:
beforeRouteEnter
actived
beforeRouteEnter
每次組件渲染的時(shí)候,都會(huì)執(zhí)行beforeRouteEnter
beforeRouteEnter(to, from, next){
next(vm=>{
console.log(vm)
// 每次進(jìn)入路由執(zhí)行
vm.getData() // 獲取數(shù)據(jù)
})
},
actived
在keep-alive
緩存的組件被激活的時(shí)候,都會(huì)執(zhí)行actived
鉤子
activated(){
this.getData() // 獲取數(shù)據(jù)
},
注意:服務(wù)器端渲染期間avtived
不被調(diào)用
感謝各位的閱讀,以上就是“vue內(nèi)置組件keep-alive怎么使用”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)vue內(nèi)置組件keep-alive怎么使用這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!
當(dāng)前題目:vue內(nèi)置組件keep-alive怎么使用
文章位置:http://fisionsoft.com.cn/article/gepdpc.html