快速开始
安装
IMPORTANT
✨ 请确保项目已安装 vue-router
✨ npm地址 https://www.npmjs.com/package/sluggard-keep-alive-vue
bash
pnpm add sluggard-keep-alive-vue
特点
兼容约定式路由插件 如 unplugin-vue-router
- 支持约定式路由页面命名为
index.vue
- 无需使用单独的
script
标签暴露页面 namevue3.3以前
- 也无需使用
defineOptions
宏设置页面 namevue3.3以后
只需为 router.meta
添加 keepAlice: boolean | Filter
属性即可控制页面缓存
router.meta.keepAlice
除boolean
类型外还支持Filter类型
- typescript
// Filter类型 用于进行页面过滤配置 interface Filter { excl?: string[] incl?: string[] }
incl
包含过滤 :- 一个由 routePath 组成的数组
- 只有从 incl 中指定的页面跳转到当前页面 当前页面 才有缓存
- 其他页面跳转至当前页, 当前页 不会有缓存
excl
排除过滤 :- 一个由 routePath 组成的数组
- 如果从 excl 中指定的页面跳转到当前页面, 当前页 不会有缓存
- 其他页面跳转至当前页, 当前页 会有缓存
提供多种方法进行缓存控制
- 页面缓存查询
- 动态添加删除页面缓存
- 滚动缓存(支持多层嵌套) 等功能
快速配置
修改 App.vue 👇
vue
<template>
<RouterView v-slot="routerViewSlot">
<KeepAlive :include="keepAliveInclude">
<component :is="setComponentName(routerViewSlot)" />
</KeepAlive>
</RouterView>
</template>
<script lang="ts" setup>
import { keepAliveInit } from 'sluggard-keep-alive-vue'
const { keepAliveInclude, setComponentName } = keepAliveInit()
</script>
使用方法
为页面 routes.meta
添加 keepAlive
参数即可 👇
常规路由
router.ts
typescript
...
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory(),
routes: [
...
{
path: '/',
component: Home,
meta: {
title: 'home',
keepAlive: true // 页面开启缓存
},
},
{
path: '/about',
component: About,
meta: {
title: 'about',
keepAlive: {
incl: ['/abc'], // 仅当从 '/abc' 页面跳转到当前页时, 当前页具有缓存
},
},
},
...
]
});
...
约定式路由
index.vue
vue
<script lang="ts" setup>
definePage({
meta: {
title: 'home',
keepAlive: {
incl: ['/abc'], // 仅当从 '/abc' 页面跳转到当前页时, 当前页具有缓存
},
},
})
</script>