Vue3除了keep-alive還有哪些實(shí)現(xiàn)頁(yè)面緩存詳解
前言
有這么一個(gè)需求:列表頁(yè)進(jìn)入詳情頁(yè)后,切換回列表頁(yè),需要對(duì)列表頁(yè)進(jìn)行緩存,如果從首頁(yè)進(jìn)入列表頁(yè),就要重新加載列表頁(yè)。
對(duì)于這個(gè)需求,我的第一個(gè)想法就是使用keep-alive來(lái)緩存列表頁(yè),列表和詳情頁(yè)切換時(shí),列表頁(yè)會(huì)被緩存;從首頁(yè)進(jìn)入列表頁(yè)時(shí),就重置列表頁(yè)數(shù)據(jù)并重新獲取新數(shù)據(jù)來(lái)達(dá)到列表頁(yè)重新加載的效果。
但是,這個(gè)方案有個(gè)很不好的地方就是:如果列表頁(yè)足夠復(fù)雜,有下拉刷新、下拉加載、有彈窗、有輪播等,在清除緩存時(shí),就需要重置很多數(shù)據(jù)和狀態(tài),而且還可能要手動(dòng)去銷毀和重新加載某些組件,這樣做既增加了復(fù)雜度,也容易出bug。
接下來(lái)說(shuō)說(shuō)我的想到的新實(shí)現(xiàn)方案(代碼基于Vue3)。
keep-alive 緩存和清除
keep-alive 緩存原理:進(jìn)入頁(yè)面時(shí),頁(yè)面組件渲染完成,keep-alive 會(huì)緩存頁(yè)面組件的實(shí)例;離開(kāi)頁(yè)面后,組件實(shí)例由于已經(jīng)緩存就不會(huì)進(jìn)行銷毀;當(dāng)再次進(jìn)入頁(yè)面時(shí),就會(huì)將緩存的組件實(shí)例拿出來(lái)渲染,因?yàn)榻M件實(shí)例保存著原來(lái)頁(yè)面的數(shù)據(jù)和Dom的狀態(tài),那么直接渲染組件實(shí)例就能得到原來(lái)的頁(yè)面。
keep-alive 最大的難題就是緩存的清理,如果能有簡(jiǎn)單的緩存清理方法,那么keep-alive 組件用起來(lái)就很爽。
但是,keep-alive 組件沒(méi)有提供清除緩存的API,那有沒(méi)有其他清除緩存的辦法呢?答案是有的。我們先看看 keep-alive 組件的props:
include - string | RegExp | Array。只有名稱匹配的組件會(huì)被緩存。
exclude - string | RegExp | Array。任何名稱匹配的組件都不會(huì)被緩存。
max - number | string。最多可以緩存多少組件實(shí)例。
從include描述來(lái)看,我發(fā)現(xiàn)include是可以用來(lái)清除緩存,做法是:將組件名稱添加到include里,組件會(huì)被緩存;移除組件名稱,組件緩存會(huì)被清除。根據(jù)這個(gè)原理,用hook簡(jiǎn)單封裝一下代碼:
import { ref, nextTick } from 'vue'
const caches = ref<string[]>([])
export default function useRouteCache () {
// 添加緩存的路由組件
function addCache (componentName: string | string []) {
if (Array.isArray(componentName)) {
componentName.forEach(addCache)
return
}
if (!componentName || caches.value.includes(componentName)) return
caches.value.push(componentName)
}
// 移除緩存的路由組件
function removeCache (componentName: string) {
const index = caches.value.indexOf(componentName)
if (index > -1) {
return caches.value.splice(index, 1)
}
}
// 移除緩存的路由組件的實(shí)例
async function removeCacheEntry (componentName: string) {
if (removeCache(componentName)) {
await nextTick()
addCache(componentName)
}
}
return {
caches,
addCache,
removeCache,
removeCacheEntry
}
}hook的用法如下:
<router-view v-slot="{ Component }">
<keep-alive :include="caches">
<component :is="Component" />
</keep-alive>
</router-view>
<script setup lang="ts">
import useRouteCache from './hooks/useRouteCache'
const { caches, addCache } = useRouteCache()
<!-- 將列表頁(yè)組件名稱添加到需要緩存名單中 -->
addCache(['List'])
</script>清除列表頁(yè)緩存如下:
import useRouteCache from '@/hooks/useRouteCache'
const { removeCacheEntry } = useRouteCache()
removeCacheEntry('List')此處removeCacheEntry方法清除的是列表組件的實(shí)例,'List' 值仍然在 組件的include里,下次重新進(jìn)入列表頁(yè)會(huì)重新加載列表組件,并且之后會(huì)繼續(xù)列表組件進(jìn)行緩存。
列表頁(yè)清除緩存的時(shí)機(jī)
進(jìn)入列表頁(yè)后清除緩存
在列表頁(yè)路由組件的beforeRouteEnter勾子中判斷是否是從其他頁(yè)面(Home)進(jìn)入的,是則清除緩存,不是則使用緩存。
defineOptions({
name: 'List1',
beforeRouteEnter (to: RouteRecordNormalized, from: RouteRecordNormalized) {
if (from.name === 'Home') {
const { removeCacheEntry } = useRouteCache()
removeCacheEntry('List1')
}
}
})這種緩存方式有個(gè)不太友好的地方:當(dāng)從首頁(yè)進(jìn)入列表頁(yè),列表頁(yè)和詳情頁(yè)來(lái)回切換,列表頁(yè)是緩存的;但是在首頁(yè)和列表頁(yè)間用瀏覽器的前進(jìn)后退來(lái)切換時(shí),我們更多的是希望列表頁(yè)能保留緩存,就像在多頁(yè)面中瀏覽器前進(jìn)后退會(huì)緩存原頁(yè)面一樣的效果。但實(shí)際上,列表頁(yè)重新刷新了,這就需要使用另一種解決辦法,點(diǎn)擊鏈接時(shí)清除緩存清除緩存。
點(diǎn)擊鏈接跳轉(zhuǎn)前清除緩存
在首頁(yè)點(diǎn)擊跳轉(zhuǎn)列表頁(yè)前,在點(diǎn)擊事件的時(shí)候去清除列表頁(yè)緩存,這樣的話在首頁(yè)和列表頁(yè)用瀏覽器的前進(jìn)后退來(lái)回切換,列表頁(yè)都是緩存狀態(tài),只要當(dāng)重新點(diǎn)擊跳轉(zhuǎn)鏈接的時(shí)候,才重新加載列表頁(yè),滿足預(yù)期。
// 首頁(yè) Home.vue
<li>
<router-link to="/list" @click="removeCacheBeforeEnter">列表頁(yè)</router-link>
</li>
<script setup lang="ts">
import useRouteCache from '@/hooks/useRouteCache'
defineOptions({
name: 'Home'
})
const { removeCacheEntry } = useRouteCache()
// 進(jìn)入頁(yè)面前,先清除緩存實(shí)例
function removeCacheBeforeEnter () {
removeCacheEntry('List')
}
</script>狀態(tài)管理實(shí)現(xiàn)緩存
通過(guò)狀態(tài)管理庫(kù)存儲(chǔ)頁(yè)面的狀態(tài)和數(shù)據(jù)也能實(shí)現(xiàn)頁(yè)面緩存。此處狀態(tài)管理使用的是pinia。
首先使用pinia創(chuàng)建列表頁(yè)store:
import { defineStore } from 'pinia'
interface Item {
id?: number,
content?: string
}
const useListStore = defineStore('list', {
// 推薦使用 完整類型推斷的箭頭函數(shù)
state: () => {
return {
isRefresh: true,
pageSize: 30,
currentPage: 1,
list: [] as Item[],
curRow: null as Item | null
}
},
actions: {
setList (data: Item []) {
this.list = data
},
setCurRow (data: Item) {
this.curRow = data
},
setIsRefresh (data: boolean) {
this.isRefresh = data
}
}
})
export default useListStore然后在列表頁(yè)中使用store:
<div>
<el-page-header @back="goBack">
<template #content>狀態(tài)管理實(shí)現(xiàn)列表頁(yè)緩存</template>
</el-page-header>
<el-table v-loading="loading" :data="tableData" border style="width: 100%; margin-top: 30px;">
<el-table-column prop="id" label="id" />
<el-table-column prop="content" label="內(nèi)容"/>
<el-table-column label="操作">
<template v-slot="{ row }">
<el-link type="primary" @click="gotoDetail(row)">進(jìn)入詳情</el-link>
<el-tag type="success" v-if="row.id === listStore.curRow?.id">剛點(diǎn)擊</el-tag>
</template>
</el-table-column>
</el-table>
<el-pagination
v-model:currentPage="listStore.currentPage"
:page-size="listStore.pageSize"
layout="total, prev, pager, next"
:total="listStore.list.length"
/>
</div>
<script setup lang="ts">
import useListStore from '@/store/listStore'
const listStore = useListStore()
...
</script>通過(guò)beforeRouteEnter鉤子判斷是否從首頁(yè)進(jìn)來(lái),是則通過(guò) listStore.$reset() 來(lái)重置數(shù)據(jù),否則使用緩存的數(shù)據(jù)狀態(tài);之后根據(jù) listStore.isRefresh 標(biāo)示判斷是否重新獲取列表數(shù)據(jù)。
defineOptions({
beforeRouteEnter (to: RouteLocationNormalized, from: RouteLocationNormalized) {
if (from.name === 'Home') {
const listStore = useListStore()
listStore.$reset()
}
}
})
onBeforeMount(() => {
if (!listStore.useCache) {
loading.value = true
setTimeout(() => {
listStore.setList(getData())
loading.value = false
}, 1000)
listStore.useCache = true
}
})缺點(diǎn)
通過(guò)狀態(tài)管理去做緩存的話,需要將狀態(tài)數(shù)據(jù)都存在stroe里,狀態(tài)多起來(lái)的話,會(huì)有點(diǎn)繁瑣,而且狀態(tài)寫(xiě)在store里肯定沒(méi)有寫(xiě)在列表組件里來(lái)的直觀;狀態(tài)管理由于只做列表頁(yè)數(shù)據(jù)的緩存,對(duì)于一些非受控組件來(lái)說(shuō),組件內(nèi)部狀態(tài)改變是緩存不了的,這就導(dǎo)致頁(yè)面渲染后跟原來(lái)有差別,需要額外代碼操作。
頁(yè)面彈窗實(shí)現(xiàn)緩存
將詳情頁(yè)做成全屏彈窗,那么從列表頁(yè)進(jìn)入詳情頁(yè),就只是簡(jiǎn)單地打開(kāi)詳情頁(yè)彈窗,將列表頁(yè)覆蓋,從而達(dá)到列表頁(yè) “緩存”的效果,而非真正的緩存。
這里還有一個(gè)問(wèn)題,打開(kāi)詳情頁(yè)之后,如果點(diǎn)后退,會(huì)返回到首頁(yè),實(shí)際上我們希望是返回列表頁(yè),這就需要給詳情彈窗加個(gè)歷史記錄,如列表頁(yè)地址為 '/list',打開(kāi)詳情頁(yè)變?yōu)?'/list?id=1'。
彈窗組件實(shí)現(xiàn):
// PopupPage.vue
<template>
<div class="popup-page" :class="[!dialogVisible && 'hidden']">
<slot v-if="dialogVisible"></slot>
</div>
</template>
<script setup lang="ts">
import { useLockscreen } from 'element-plus'
import { computed, defineProps, defineEmits } from 'vue'
import useHistoryPopup from './useHistoryPopup'
const props = defineProps({
modelValue: {
type: Boolean,
default: false
},
// 路由記錄
history: {
type: Object
},
// 配置了history后,初次渲染時(shí),如果有url上有history參數(shù),則自動(dòng)打開(kāi)彈窗
auto: {
type: Boolean,
default: true
},
size: {
type: String,
default: '50%'
},
full: {
type: Boolean,
default: false
}
})
const emit = defineEmits(
['update:modelValue', 'autoOpen', 'autoClose']
)
const dialogVisible = computed<boolean>({ // 控制彈窗顯示
get () {
return props.modelValue
},
set (val) {
emit('update:modelValue', val)
}
})
useLockscreen(dialogVisible)
useHistoryPopup({
history: computed(() => props.history),
auto: props.auto,
dialogVisible: dialogVisible,
onAutoOpen: () => emit('autoOpen'),
onAutoClose: () => emit('autoClose')
})
</script>
<style lang='less'>
.popup-page {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
z-index: 100;
overflow: auto;
padding: 10px;
background: #fff;
&.hidden {
display: none;
}
}
</style>彈窗組件調(diào)用:
<popup-page
v-model="visible"
full
:history="{ id: id }">
<Detail></Detail>
</popup-page>缺點(diǎn)
彈窗實(shí)現(xiàn)頁(yè)面緩存,局限比較大,只能在列表頁(yè)和詳情頁(yè)中才有效,離開(kāi)列表頁(yè)之后,緩存就會(huì)失效,比較合適一些簡(jiǎn)單緩存的場(chǎng)景。
父子路由實(shí)現(xiàn)緩存
該方案原理其實(shí)就是頁(yè)面彈窗,列表頁(yè)為父路由,詳情頁(yè)為子路由,從列表頁(yè)跳轉(zhuǎn)到詳情頁(yè)時(shí),顯示詳情頁(yè)字路由,且詳情頁(yè)全屏顯示,覆蓋住列表頁(yè)。
聲明父子路由:
{
path: '/list',
name: 'list',
component: () => import('./views/List.vue'),
children: [
{
path: '/detail',
name: 'detail',
component: () => import('./views/Detail.vue'),
}
]
}列表頁(yè)代碼:
// 列表頁(yè)
<template>
<el-table v-loading="loading" :data="tableData" border style="width: 100%; margin-top: 30px;">
<el-table-column prop="id" label="id" />
<el-table-column prop="content" label="內(nèi)容"/>
<el-table-column label="操作">
<template v-slot="{ row }">
<el-link type="primary" @click="gotoDetail(row)">進(jìn)入詳情</el-link>
<el-tag type="success" v-if="row.id === curRow?.id">剛點(diǎn)擊</el-tag>
</template>
</el-table-column>
</el-table>
<el-pagination
v-model:currentPage="currentPage"
:page-size="pageSize"
layout="total, prev, pager, next"
:total="list.length"
/>
<!-- 詳情頁(yè) -->
<router-view class="popyp-page"></router-view>
</template>
<style lang='less' scoped>
.popyp-page {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 100;
background: #fff;
overflow: auto;
}
</style>總結(jié)
到此這篇關(guān)于Vue3除了keep-alive還有哪些實(shí)現(xiàn)頁(yè)面緩存的文章就介紹到這了,更多相關(guān)Vue3頁(yè)面緩存內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Vue中Keep-Alive緩存組件使用語(yǔ)法及原理深度解析
- React實(shí)現(xiàn)頁(yè)面狀態(tài)緩存(keep-alive)的示例代碼
- Vue路由組件的緩存keep-alive和include屬性的具體使用
- Vue keep-alive組件的使用及如何清除緩存
- vue3?keep-alive實(shí)現(xiàn)tab頁(yè)面緩存功能
- Vue3嵌套路由中使用keep-alive緩存多層的實(shí)現(xiàn)
- vue使用keep-alive進(jìn)行組件緩存方法詳解(組件不緩存問(wèn)題解決)
- vue中keep-alive組件實(shí)現(xiàn)多級(jí)嵌套路由的緩存
- 快速解決 keep-alive 緩存組件中定時(shí)器干擾問(wèn)題
相關(guān)文章
詳解vue服務(wù)端渲染瀏覽器端緩存(keep-alive)
在使用服務(wù)器端渲染時(shí),除了服務(wù)端的接口緩存、頁(yè)面緩存、組建緩存等,瀏覽器端也避免不了要使用緩存,減少頁(yè)面的重繪。這篇文章主要介紹了詳解vue服務(wù)端渲染瀏覽器端緩存(keep-alive),感興趣的小伙伴們可以參考一下2018-10-10
element?ui?watch?el-input賦值之后無(wú)法刪除或修改問(wèn)題
這篇文章主要介紹了element?ui?watch?el-input賦值之后無(wú)法刪除或修改問(wèn)題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
如何在Vue3和Vite項(xiàng)目中用SQLite數(shù)據(jù)庫(kù)進(jìn)行數(shù)據(jù)存儲(chǔ)
SQLite是一種嵌入式關(guān)系型數(shù)據(jù)庫(kù)管理系統(tǒng),是一個(gè)零配置、無(wú)服務(wù)器的、自給自足的、事務(wù)性的SQL數(shù)據(jù)庫(kù)引擎,這篇文章主要給大家介紹了關(guān)于如何在Vue3和Vite項(xiàng)目中用SQLite數(shù)據(jù)庫(kù)進(jìn)行數(shù)據(jù)存儲(chǔ)的相關(guān)資料,需要的朋友可以參考下2024-03-03
Vue如何使用js-audio-recorder插件實(shí)現(xiàn)錄音功能并將文件轉(zhuǎn)成wav上傳
這篇文章主要給大家介紹了關(guān)于Vue如何使用js-audio-recorder插件實(shí)現(xiàn)錄音功能并將文件轉(zhuǎn)成wav上傳的相關(guān)資料,文中通過(guò)示例代碼講解了彈窗界面、變量控制、錄音啟動(dòng)與停止、波形可視化、文件上傳及WAV格式獲取的完整流程,需要的朋友可以參考下2025-06-06
vue動(dòng)態(tài)的 BreadCrumb 組件el-breadcrumb ElementUI詳解
這篇文章主要介紹了vue如何做一個(gè)動(dòng)態(tài)的 BreadCrumb 組件,el-breadcrumb ElementUI2024-07-07
,本文通過(guò)圖文示例代碼相結(jié)合給大家介紹的非常詳細(xì),需要的朋友可以參考下
Vue+Echarts報(bào)錯(cuò)Cannot?set?properties?of?undefined?(settin
這篇文章主要介紹了Vue+Echarts報(bào)錯(cuò)Cannot?set?properties?of?undefined?(setting?‘plate‘)的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08
vue-cli3項(xiàng)目在IE瀏覽器打開(kāi)兼容問(wèn)題及解決
這篇文章主要介紹了vue-cli3項(xiàng)目在IE瀏覽器打開(kāi)兼容問(wèn)題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08
iview form清除校驗(yàn)狀態(tài)的實(shí)現(xiàn)
這篇文章主要介紹了iview form清除校驗(yàn)狀態(tài)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09

