另一种方法
一般都是通过控制 router 配置中的 meta 信息实现。这种方法通过控制 exclude 的值,动态的控制 keep-alive 中的缓存。
hook
使用 hook 的形式,使逻辑更集中
// useKeepAlive
/**
* 默认所有添加到配置中的 route 都需要 keep-alive,其 componentName 都会包括到 include 中
* 通过控制 exclude 的值,动态的控制 keep-alive 中的缓存
* 其原理和 meta 是相同的,这种写法不需要到 router 配置中添加额外的信息
*
*
* 配置 keepAliveConfig 控制哪些页面需要 keep-alive
* keepAliveRouteName:需要 keep-alive 的路由名称
* keepAliveToRouteNameArr:当前 keep-alive 的路由 to 哪些路由不会清理掉,当前 keep-alive 路由的缓存
* componentName:需要 keep-alive 组件的 name
*
*
* noKeepAlive:在 router 跳转时,params 信息中添加 noKeepAlive 可以不加载需要跳转页面的 keep-alive 缓存
**/
import { ref } from '@vue/composition-api'
const keepAliveConfig = [
// Swagger
{
keepAliveRouteName: 'swagger',
keepAliveFromRouteNameArr: ['cmsAppDetail'],
componentName: 'Swagger'
}
]
export const include = ref(keepAliveConfig.map(el => el.componentName))
export const exclude = ref([])
export const maxKeepAlive = ref(5)
function handleExclude(keepAliveObj) {
// 清除掉 keep alive 缓存
exclude.value = [keepAliveObj.componentName]
// 继续添加缓存
setTimeout(() => {
exclude.value = []
}, 100)
}
export function keepAliveController(to, from) {
const fromKeepAliveObj = keepAliveConfig.find(el => el.keepAliveRouteName === from.name)
const toKeepAliveObj = keepAliveConfig.find(el => el.keepAliveRouteName === to.name)
// when other to keep-alive route
// route params 信息中带 noKeepAlive 时,无缓存跳转
if (to.params && to.params.noKeepAlive) {
handleExclude(toKeepAliveObj)
return
}
// when keep-alive route to other
if (!fromKeepAliveObj) return // 路由未设置 keep alive 则跳过
const isKeepAlive = fromKeepAliveObj.keepAliveToRouteNameArr.includes(to.name)
if (!isKeepAlive) {
handleExclude(fromKeepAliveObj)
}
}
}
在 Vue 组件中的使用
添加控制逻辑到 router.afterEach 中