Vue3緩存之路由緩存與Pinia狀態(tài)緩存詳解
Vue3緩存兩種:路由緩存與Pinia狀態(tài)緩存
單頁應用中,最令人頭疼的就是頁面刷新或者回退時,數(shù)據(jù)丟失或重新加載的問題。
本文以微小demo介紹兩種緩存以應付Vue3項目中的絕大多數(shù)需要緩存的業(yè)務(wù)。
路由緩存
一個令人頭疼的問題是,當路由后退或原地刷新時,組件的生命周期會被重新觸發(fā),即可能導致生命周期鉤子中加載數(shù)據(jù)的函數(shù)被觸發(fā),為了避免這種情況,可以利用Vue-Router的路由緩存機制。
以一個文章列表為例,假設(shè)你點擊了一篇文章進行閱讀,并希望返回時不要重載數(shù)據(jù)或觸發(fā)生命周期鉤子,你可以在router配置中,為文章列表頁面的meta選項加上keepAlive屬性,并設(shè)置為true:
{
path : '/articleList',
name : 'articleList',
component: ()=>import('@/view/article/ArticleListView.vue'),
meta: { keepAlive:true } // 此處添加
}然后找到router-view組件,并對其進行改寫:
<router-view v-slot="{ Component }">
<keep-alive>
<component :is="Component" v-if="$route.meta.keepAlive"/>
</keep-alive>
<component :is="Component" v-if="!$route.meta.keepAlive"/>
</router-view>這樣就完成了對文章列表頁面的緩存。如果你需要為其他頁面進行緩存,則可以按需為其路由配置keepAlive屬性
Pinia狀態(tài)緩存
一種場景是,我們有一行Type標簽,點擊其可以加載不同分類下的文章列表,而這個Type會被我們納入狀態(tài)管理。
一個尷尬的事實是,當頁面刷新或者路由回退時,Type也隨之被重置,丟失了原來的狀態(tài)。為此,可以使用Pinia的額外插件,實現(xiàn)其緩存:
npm i pinia-plugin-persist --save
安裝完成后,在main.js文件中,進行如下配置:
import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist' // 注意此處
const pinia = createPinia()
pinia.use(piniaPluginPersist) // 注意此處
const app = createApp(App)
app.use(pinia)然后回到我們的store.js中進行配置,假設(shè)針對Type進行狀態(tài)管理并緩存,可以配置其persist選項下的enabled屬性為true:
export const useNowTypeStore = defineStore('nowType', () => {
const nowType = ref(0)
function setNowType(realType) {
nowType.value = realType
}
return {nowType, setNowType}
}, {
persist: {
enabled: true
}
} // 注意此處
)這樣就完成了對NowType的緩存。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue3中$attrs的變化與inheritAttrs的使用詳解
$attrs現(xiàn)在包括class和style屬性。?也就是說在vue3中$listeners不存在了,vue2中$listeners是單獨存在的,在vue3?$attrs包括class和style屬性,?vue2中?$attrs?不包含class和style屬性,這篇文章主要介紹了vue3中$attrs的變化與inheritAttrs的使用?,需要的朋友可以參考下2022-10-10
vue3配置Element及element-plus/lib/theme-chalk/index.css報錯的解決
這篇文章主要介紹了vue3配置Element及element-plus/lib/theme-chalk/index.css報錯的解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03

