【发布时间】:2018-04-03 23:35:12
【问题描述】:
我正在尝试为我的一些路由组件有条件地设置保持活动状态,并能够清除缓存的路由并设置新的缓存路由。 我下面的代码有效,但我无法清除缓存的组件。
我在要缓存的路线上有元道具
{
name: 'Route1',
path: '/route1',
component: lazyLoading('route1', true),
meta: {
auth: true,
cacheRoute: 'Route1',
},
},
{
name: 'Route2',
path: '/route2',
component: lazyLoading('route1', true),
meta: {
auth: true,
cacheRoute: 'Route2',
},
},
然后我在路由器上使用 beforeEach 方法。
router.beforeEach((to, from, next) => {
if (to.meta.cacheRoute && store.getters.cachedRouteObject.cached !==
to.meta.cacheRoute)
store.dispatch('cacheRoute', {
cached: to.meta.cacheRoute,
uncached: from.meta.cacheRoute,
}).then(() => {
next();
});
next();
});
并像这样使用 vuex cachedRouteObject:
<keep-alive :include="cachedRouteObject.cached"
:exclude="cachedRouteObject.uncached">
<router-view></main-router-view>
</keep-alive>
关键是,随着时间的推移,当我从一个路由切换到另一个路由时,所有必须缓存的组件都会保持缓存状态,因此我最终会得到许多缓存的组件。而不仅仅是 1. 似乎排除属性不像我预期的那样工作。关于如何始终只缓存一个路由组件的任何想法。
【问题讨论】:
标签: vue.js vuejs2 vue-router