vue中的keep-alive詳解與應(yīng)用場(chǎng)景

一、Keep-alive 是什么
keep-alive是vue中的內(nèi)置組件,能在組件切換過(guò)程中將狀態(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的基本用法:
<keep-alive> <component :is="view"></component> </keep-alive>
使用includes和exclude:
<keep-alive include="a,b"> <component :is="view"></component> </keep-alive> ? <!-- 正則表達(dá)式 (使用 `v-bind`) --> <keep-alive :include="/a|b/"> <component :is="view"></component> </keep-alive> ? <!-- 數(shù)組 (使用 `v-bind`) --> <keep-alive :include="['a', 'b']"> <component :is="view"></component> </keep-alive>
匹配首先檢查組件自身的 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í)候可以按需來(lái)控制頁(yè)面的keep-alive
在路由中設(shè)置keepAlive屬性判斷是否需要緩存
{
path: 'list',
name: 'itemList', // 列表頁(yè)
component (resolve) {
require(['@/pages/item/list'], resolve)
},
meta: {
keepAlive: true,
title: '列表頁(yè)'
}
}使用<keep-alive>
<div id="app" class='wrapper'>
<keep-alive>
<!-- 需要緩存的視圖組件 -->
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<!-- 不需要緩存的視圖組件 -->
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>三、原理分析
keep-alive是vue中內(nèi)置的一個(gè)組件
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)
}
/* 如果沒(méi)有命中緩存,則將其設(shè)置進(jìn)緩存 */
else {
cache[key] = vnode
keys.push(key)
// prune oldest entry
/* 如果配置了max并且緩存的長(zhǎng)度超過(guò)了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])
}
}可以看到該組件沒(méi)有template,而是用了render,在組件渲染的時(shí)候會(huì)自動(dòng)執(zhí)行render函數(shù)
this.cache是一個(gè)對(duì)象,用來(lái)存儲(chǔ)需要緩存的組件,它將以如下形式存儲(chǔ):
this.cache = {
'key1':'組件1',
'key2':'組件2',
// ...
}在組件銷毀的時(shí)候執(zhí)行pruneCacheEntry函數(shù)
function pruneCacheEntry (
cache: VNodeCache,
key: string,
keys: Array<string>,
current?: VNode
) {
const cached = cache[key]
/* 判斷當(dāng)前沒(méi)有處于被渲染狀態(tài)的組件,將其銷毀*/
if (cached && (!current || cached.tag !== current.tag)) {
cached.componentInstance.$destroy()
}
cache[key] = null
remove(keys, key)
}在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的順序,將其從原來(lái)的地方刪掉并重新放在最后一個(gè) */
remove(keys, key)
keys.push(key)
} 直接從緩存中拿 vnode 的組件實(shí)例,此時(shí)重新調(diào)整該組件key的順序,將其從原來(lái)的地方刪掉并重新放在this.keys中最后一個(gè)
this.cache對(duì)象中沒(méi)有該key值的情況,如下:
/* 如果沒(méi)有命中緩存,則將其設(shè)置進(jìn)緩存 */
else {
cache[key] = vnode
keys.push(key)
/* 如果配置了max并且緩存的長(zhǎng)度超過(guò)了this.max,則從緩存中刪除第一個(gè) */
if (this.max && keys.length > parseInt(this.max)) {
pruneCacheEntry(cache, keys[0], keys, this._vnode)
}
}表明該組件還沒(méi)有被緩存過(guò),則以該組件的key為鍵,組件vnode為值,將其存入this.cache中,并且把key存入this.keys中
此時(shí)再判斷this.keys中緩存組件的數(shù)量是否超過(guò)了設(shè)置的最大緩存數(shù)量值this.max,如果超過(guò)了,則把第一個(gè)緩存組件刪掉
四、案例實(shí)現(xiàn)
緩存包裹在其中的動(dòng)態(tài)切換組件
<KeepAlive> 包裹動(dòng)態(tài)組件時(shí),會(huì)緩存不活躍的組件實(shí)例,而不是銷毀它們。
任何時(shí)候都只能有一個(gè)活躍組件實(shí)例作為 <KeepAlive> 的直接子節(jié)點(diǎn)。
完整案例:08_dynamic/52_keep-alive.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>動(dòng)態(tài)組件</title>
</head>
<body>
<div id="app">
<ul>
<li @click="currentTab='Home'">首頁(yè)</li>
<li @click="currentTab='Kind'">分類</li>
<li @click="currentTab='Cart'">購(gòu)物車</li>
<li @click="currentTab='User'">我的</li>
</ul>
<!-- 動(dòng)態(tài)組件默認(rèn)切換時(shí) 執(zhí)行的是組件的 銷毀 和 重新創(chuàng)建 -->
<!-- 可以使用 KeepAlive 保留組件的狀態(tài),避免組件的重新渲染 -->
<keep-alive>
<component :is="currentTab"></component>
</keep-alive>
</div>
</body>
<script src="../lib/vue.global.js"></script>
<script>
const Home = {
template: `
<div>
首頁(yè) <input placeholder="首頁(yè)"/>
</div>
`,
created () { console.log('Home created') },
mounted () { console.log('Home mounted') },
unmounted () { console.log('Home unmounted') }
}
const Kind = {
template: `
<div>
分類 <input placeholder="分類"/>
</div>
`,
created () { console.log('Kind created') },
mounted () { console.log('Kind mounted') },
unmounted () { console.log('Kind unmounted') }
}
const Cart = {
template: `
<div>
購(gòu)物車 <input placeholder="購(gòu)物車"/>
</div>
`,
created () { console.log('Cart created') },
mounted () { console.log('Cart mounted') },
unmounted () { console.log('Cart unmounted') }
}
const User = {
template: `
<div>
我的 <input placeholder="我的"/>
</div>
`,
created () { console.log('User created') },
mounted () { console.log('User mounted') },
unmounted () { console.log('User unmounted') }
}
?
Vue.createApp({
data () {
return {
currentTab: 'Home'
}
},
components: {
Home,
Kind,
Cart,
User
}
}).mount('#app')
</script>
</html>
當(dāng)一個(gè)組件在
<KeepAlive>中被切換時(shí),它的activated和deactivated生命周期鉤子將被調(diào)用,用來(lái)替代mounted和unmounted。這適用于<KeepAlive>的直接子節(jié)點(diǎn)及其所有子孫節(jié)點(diǎn)。
activated、deactivated鉤子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>動(dòng)態(tài)組件</title>
</head>
<body>
<div id="app">
<ul>
<li @click="currentTab='Home'">首頁(yè)</li>
<li @click="currentTab='Kind'">分類</li>
<li @click="currentTab='Cart'">購(gòu)物車</li>
<li @click="currentTab='User'">我的</li>
</ul>
<!-- 動(dòng)態(tài)組件默認(rèn)切換時(shí) 執(zhí)行的是組件的 銷毀 和 重新創(chuàng)建 -->
<!-- 可以使用 KeepAlive 保留組件的狀態(tài),避免組件的重新渲染 -->
<keep-alive>
<component :is="currentTab"></component>
</keep-alive>
</div>
</body>
<script src="../lib/vue.global.js"></script>
<script>
const Home = {
template: `
<div>
首頁(yè) <input placeholder="首頁(yè)"/>
</div>
`,
created () { console.log('Home created') },
mounted () { console.log('Home mounted') },
unmounted () { console.log('Home unmounted') },
activated () { console.log('Home 顯示')},
deactivated () { console.log('Home 隱藏')}
}
const Kind = {
template: `
<div>
分類 <input placeholder="分類"/>
</div>
`,
created () { console.log('Kind created') },
mounted () { console.log('Kind mounted') },
unmounted () { console.log('Kind unmounted') },
activated () { console.log('Kind 顯示')},
deactivated () { console.log('Kind 隱藏')}
}
const Cart = {
template: `
<div>
購(gòu)物車 <input placeholder="購(gòu)物車"/>
</div>
`,
created () { console.log('Cart created') },
mounted () { console.log('Cart mounted') },
unmounted () { console.log('Cart unmounted') },
activated () { console.log('Cart 顯示')},
deactivated () { console.log('Cart 隱藏')}
}
const User = {
template: `
<div>
我的 <input placeholder="我的"/>
</div>
`,
created () { console.log('User created') },
mounted () { console.log('User mounted') },
unmounted () { console.log('User unmounted') },
activated () { console.log('User 顯示')},
deactivated () { console.log('User 隱藏')}
}
?
Vue.createApp({
data () {
return {
currentTab: 'Home'
}
},
components: {
Home,
Kind,
Cart,
User
}
}).mount('#app')
</script>
</html>要不不緩存,要緩存都緩存了,這樣不好
使用 include / exclude可以設(shè)置哪些組件被緩存,使用 max可以設(shè)定最多緩存多少個(gè)
<!-- 用逗號(hào)分隔的字符串,中間不要家空格 -->
<KeepAlive include="a,b">
<component :is="view"></component>
</KeepAlive>
?
<!-- 正則表達(dá)式 (使用 `v-bind`) -->
<KeepAlive :include="/a|b/">
<component :is="view"></component>
</KeepAlive>
?
<!-- 數(shù)組 (使用 `v-bind`) -->
<KeepAlive :include="['a', 'b']">
<component :is="view"></component>
</KeepAlive>組件如果想要條件性地被 KeepAlive 緩存,就必須顯式聲明一個(gè) name 選項(xiàng)。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>動(dòng)態(tài)組件</title>
</head>
<body>
<div id="app">
<ul>
<li @click="currentTab='Home'">首頁(yè)</li>
<li @click="currentTab='Kind'">分類</li>
<li @click="currentTab='Cart'">購(gòu)物車</li>
<li @click="currentTab='User'">我的</li>
</ul>
<!-- 動(dòng)態(tài)組件默認(rèn)切換時(shí) 執(zhí)行的是組件的 銷毀 和 重新創(chuàng)建 -->
<!-- 可以使用 KeepAlive 保留組件的狀態(tài),避免組件的重新渲染 -->
<!-- 字符串逗號(hào)分隔,千萬(wàn)不要加空格 -->
<!-- <keep-alive include="home,user">
<component :is="currentTab"></component>
</keep-alive> -->
<!-- 正則 -->
<!-- <keep-alive :include="/home|user/">
<component :is="currentTab"></component>
</keep-alive> -->
<!-- 數(shù)組 -->
<keep-alive :include="['home', 'user']">
<component :is="currentTab"></component>
</keep-alive>
</div>
</body>
<script src="../lib/vue.global.js"></script>
<script>
const Home = {
name: 'home',
template: `
<div>
首頁(yè) <input placeholder="首頁(yè)"/>
</div>
`,
created () { console.log('Home created') },
mounted () { console.log('Home mounted') },
unmounted () { console.log('Home unmounted') },
activated () { console.log('Home 顯示')},
deactivated () { console.log('Home 隱藏')}
}
const Kind = {
name: 'kind',
template: `
<div>
分類 <input placeholder="分類"/>
</div>
`,
created () { console.log('Kind created') },
mounted () { console.log('Kind mounted') },
unmounted () { console.log('Kind unmounted') },
activated () { console.log('Kind 顯示')},
deactivated () { console.log('Kind 隱藏')}
}
const Cart = {
name: 'cart',
template: `
<div>
購(gòu)物車 <input placeholder="購(gòu)物車"/>
</div>
`,
created () { console.log('Cart created') },
mounted () { console.log('Cart mounted') },
unmounted () { console.log('Cart unmounted') },
activated () { console.log('Cart 顯示')},
deactivated () { console.log('Cart 隱藏')}
}
const User = {
name: 'user',
template: `
<div>
我的 <input placeholder="我的"/>
</div>
`,
created () { console.log('User created') },
mounted () { console.log('User mounted') },
unmounted () { console.log('User unmounted') },
activated () { console.log('User 顯示')},
deactivated () { console.log('User 隱藏')}
}
?
Vue.createApp({
data () {
return {
currentTab: 'Home'
}
},
components: {
Home,
Kind,
Cart,
User
}
}).mount('#app')
</script>
</html>五、緩存后如何獲取數(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)用
到此這篇關(guān)于vue中的keep-alive詳解與應(yīng)用場(chǎng)景的文章就介紹到這了,更多相關(guān)vue keep-alive內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue.js實(shí)現(xiàn)價(jià)格格式化的方法
這里分享一個(gè)常用的價(jià)格格式化的一個(gè)方法,在電商的價(jià)格處理中非常的實(shí)用,具體實(shí)現(xiàn)代碼大家參考下本文2017-05-05
Vue3組合式API中使用forwardRef()函數(shù)
本文主要介紹了Vue3組合式API中使用forwardRef()函數(shù),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
前端H5微信支付寶支付實(shí)現(xiàn)方法(uniapp為例)
最近上線一個(gè)項(xiàng)目,手機(jī)網(wǎng)站進(jìn)行調(diào)起支付寶App支付,做起來(lái)還是滿順手的,在此做個(gè)記錄,這篇文章主要給大家介紹了關(guān)于前端H5微信支付寶支付實(shí)現(xiàn)方法的相關(guān)資料,需要的朋友可以參考下2024-04-04
vue3子組件如何修改父組件傳過(guò)來(lái)的props數(shù)據(jù)
周所周知vue的props是單向數(shù)據(jù)流,可以從父組件中改變傳往子組件的props,反之則不行,下面這篇文章主要給大家介紹了關(guān)于vue3子組件如何修改父組件傳過(guò)來(lái)的props數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下2022-10-10
vue單頁(yè)應(yīng)用加百度統(tǒng)計(jì)代碼(親測(cè)有效)
這篇文章主要介紹了vue單頁(yè)應(yīng)用加百度統(tǒng)計(jì)代碼的解決方法,需要的朋友參考下吧2018-01-01
vue在自定義組件中使用v-model進(jìn)行數(shù)據(jù)綁定的方法
這篇文章主要介紹了vue在自定義組件中使用v-model進(jìn)行數(shù)據(jù)綁定的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
Vue中的@blur事件 當(dāng)元素失去焦點(diǎn)時(shí)所觸發(fā)的事件問(wèn)題
這篇文章主要介紹了Vue中的@blur事件 當(dāng)元素失去焦點(diǎn)時(shí)所觸發(fā)的事件問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08

