vue 利用 keepAlive 达到 a页面进入b页面缓存,但是进入c页面不会缓存该a页面
- 创建一个 mixins 文件,完成该页面功能
- 注意:
- 初始化事件不能再放置在created 、mounted 事件中了,需要自己写一个init事件
- bug: 进入详情页再进入其他页面,重新进入该页面,该页面状态依旧被保存,执行 onSearch 事件
- 优化: 强制清除该页面得keepAlive缓存(如果你不需要出去页面清除缓存,并且可以存在多个keepAlive页面,只是做进入该页面得刷新,可以删除 beforeRouteLeave 路由守卫)
export default {
data() {
return {
isFirstEntry: true,
isKeepAliveRouterList: [],
};
},
created() {},
activated() {
if (this.$route.meta.isBack) {
if (this.isFirstEntry) {
this.isFirstEntry = false;
this.init();
} else this.onSearch();
} else {
if (this.isFirstEntry) this.isFirstEntry = false;
this.init();
}
},
methods: {
init() {
console.log(
"页面初次进入刷新所有数据,如果该提示存在,你的页面不存在init函数!"
);
},
onSearch() {
console.log(
"详情页跳回该页面,如果该提示存在,你的页面不存在onSearch函数,查看页面是否需要按照当前条件刷新!"
);
},
setIsKeepAliveRouterList(routeMeta, that) {
let isKeepAliveRouterList = [];
if (
routeMeta.isKeepAliveRouterList &&
Array.isArray(routeMeta.isKeepAliveRouterList)
) {
isKeepAliveRouterList = [
...routeMeta.isKeepAliveRouterList,
...that.isKeepAliveRouterList,
];
} else {
isKeepAliveRouterList = [...that.isKeepAliveRouterList];
}
return isKeepAliveRouterList;
},
removeKeepAliveCacheForVueInstance(vueInstance) {
let key =
vueInstance.$vnode.key ??
vueInstance.$vnode.componentOptions.Ctor.cid +
(vueInstance.$vnode.componentOptions.tag
? `::${vueInstance.$vnode.componentOptions.tag}`
: "");
let cache = vueInstance.$vnode.parent.componentInstance.cache;
let keys = vueInstance.$vnode.parent.componentInstance.keys;
if (cache[key]) {
vueInstance.$destroy();
delete cache[key];
let index = keys.indexOf(key);
if (index > -1) {
keys.splice(index, 1);
}
}
},
},
beforeRouteEnter(to, from, next) {
next((vm) => {
let isKeepAliveRouterList = vm.setIsKeepAliveRouterList(to.meta, vm);
if (isKeepAliveRouterList.includes(from.path)) {
to.meta.isBack = true;
} else {
to.meta.isBack = false;
}
});
},
beforeRouteLeave(to, from, next) {
let isKeepAliveRouterList = this.setIsKeepAliveRouterList(from.meta, this);
if (!isKeepAliveRouterList.includes(to.path)) {
this.isFirstEntry = true;
this.removeKeepAliveCacheForVueInstance(this);
}
next();
},
};
export default [
{
path: '/a',
name: 'A',
component: () => import('@/a'),
meta: { keepAlive: true, isBack: false, isKeepAliveRouterList: ['/b'] }
}
]
<keep-alive max="1" >
<router-view v-if="this.$route.meta.keepAlive" :key="$route.path"/>
</keep-alive>
<router-view v-if="!this.$route.meta.keepAlive" />