Vue3缓存两种:路由缓存与Pinia状态缓存
单页应用中,最令人头疼的就是页面刷新或者回退时,数据丢失或重新加载的问题。本文以微小demo介绍两种缓存以应付Vue3项目中的绝大多数需要缓存的业务。
路由缓存
一个令人头疼的问题是,当路由后退或原地刷新时,组件的生命周期会被重新触发,即可能导致生命周期钩子中加载数据的函数被触发,为了避免这种情况,可以利用Vue-Router的路由缓存机制。以一个文章列表为例,假设你点击了一篇文章进行阅读,并希望返回时不要重载数据或触发生命周期钩子,你可以在router配置中,为文章列表页面的meta
选项加上keepAlive
属性,并设置为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状态缓存
一种场景是,我们有一行Type标签,点击其可以加载不同分类下的文章列表,而这个Type会被我们纳入状态管理。一个尴尬的事实是,当页面刷新或者路由回退时,Type也随之被重置,丢失了原来的状态。为此,可以使用Pinia的额外插件,实现其缓存:
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
中进行配置,假设针对Type进行状态管理并缓存,可以配置其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的缓存。