如果想让vue的所有页面都保持keepAlive的状态。只需要在app.vue的router-view外面套一层keep-alive
<keep-alive>
<router-view></router-view>
</keep-alive>
如果只想让某些路由保持keepAlive,只需要向keep-alive传入include(不想让某些路由keepAlive,其他的都keepAlive。则需传入exclude)
<keep-alive :include=['router-name1', 'router-name2']>
<router-view></router-view>
</keep-alive>
而include的数组完全可以通过函数获取。所以只需要在router.js中,在定义每个路由时说明其是keepAlive,并且在app.js中能够获取到该状态即可。这里给出的做法是定义路由时,通过meta给出状态,并将该状态的路由存入sessionStorage,在app.js中再通过sessionStorage取出来。
import Router from 'vue-router'
const routes = [
{
name: 'home',
path: '/home',
component: () => import('..xxx'),
meta: {
title: 'xxx',
desc: 'xxx',
keepAlive: true
}
}
]
const router = new Router({
routes
})
const includeRouters = sessionStorage.get('keepAliveRouters') || [] //需自己封装sessionStorage
router.beforeEach(function (to, from, next) {
if (to.meta) {
if (to.meta.keepAlive) {
includeRouters.push(router.name) //建议自己封装pushX,已经存入则不必再存
} else {
includeRouters.remove(router.name) // 自己封装remove,如果已经存入,则取出
}
sessionStorage.set('keepAliveRouters', includeRouters)
}
next()
}
export default router
此时,在进入某个路由前,路由的地址已经存入了sessionStorage
app.vue中需要watch $router ,并从sessionStorage中取出,放到data里。
keepAlive的:include再返回data中刚放入的地址数组
网友评论