vue中keepAlive动态缓存方法
在项目中,会遇到列表页到详情页,然后回到列表页还停留在当前位置,退出列表页后取消页面缓存的需求,所以就用到了keepAlive动态缓存方法第一步:在路由里配置开启缓存:{path: '/p/:id/:pinyin',name: 'Atlas',component: () => import('@/pages/atlas'),meta: {requiresAuth: false,title:
·
在项目中,会遇到列表页到详情页,然后回到列表页还停留在当前位置,退出列表页后取消页面缓存的需求,所以就用到了keepAlive动态缓存方法
第一步:
在路由里配置开启缓存:
{
path: '/p/:id/:pinyin',
name: 'Atlas',
component: () => import('@/pages/atlas'),
meta: {
requiresAuth: false,
title: '图集',
keepAlive: true // 加上这个需要缓存
}
},
然后在app.vue配置:
这里的include意思想必大家都知道其含义: include是需要缓存的组件;
<div id="app">
<keep-alive :include="cachedViews">
<router-view v-wechat-title="title" v-if="this.$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view :key="key" v-wechat-title="title" v-if="!this.$route.meta.keepAlive"></router-view>
</div>
data里面:
data() {
return {
cachedViews: []
}
},
要使用watch来监听路由的变化
watch: {
//监听动态缓存动态赋值控制页面是否缓存
$route: {
handler:function(to,from){
this.cachedViews = this.$store.state.cacheView;
}
}
}
第二步:
然后在store里面配置:
state:
state: {
//需要缓存的组件name
cacheView: ['StrategyPage','Atlas','VideoPage','JudgeList']
},
mutations:
mutations: {
// 动态添加及删除缓存
ADD_CACHE_VIEW: (state, view) => {
state.cacheView.push(view)
},
DELETE_CACHE_VIEW: (state, index) => {
state.cacheView.splice(index, 1)
}
},
actions:
actions: {
// 动态添加及删除缓存
addCacheView ({ commit, state }, view) {
if (!state.cacheView.includes(view)) {
commit('ADD_CACHE_VIEW', view)
}
},
deleteCacheView ({ commit, state }, view) {
const index = state.cacheView.indexOf(view)
if (index > -1) {
commit('DELETE_CACHE_VIEW', index)
}
}
},
使用方法(在需要的地方调用):
//添加动态缓存 addCacheView是方法名,CompetitionDetail是组件name
this.$store.dispatch('addCacheView', 'CompetitionDetail');
// 删除动态缓存
this.$store.dispatch('deleteCacheView', 'CompetitionDetail')
使用中需要注意的是: 在需要缓存的页面里面必须加上name名称才有效
export default {
name: 'CompetitionDetail',
data(){
return{
}
}
}
到此配置后就可以实现动态缓存了,目前还在使用中,未出现bug,感谢大家浏览,觉得这篇对你有帮助的猿友们给个一键三连!!!
更多推荐



所有评论(0)