一、问题背景:
项目中使用一个公共组件,由后端返回不同的模版、事件类型,创建不同的路由页面。
需求:和普通的页面一样,实现通过keepAlive实现缓存,打开tab后切换页面再次切换回来的时候,查询条件和数据都在。
二、问题产生的原因:
由于keepalive使用include或者exclude去匹配组件(组件的name)进行缓存匹配;tab更新也是根据include或者exclude动态添加取消缓存。
function pruneCache (keepAliveInstance: any, filter: Function) {
const { cache, keys, _vnode } = keepAliveInstance
for (const key in cache) {
const cachedNode: ?VNode = cache[key]
if (cachedNode) {
const name: ?string = getComponentName(cachedNode.componentOptions)
if (name && !filter(name)) {
pruneCacheEntry(cache, key, keys, _vnode)
}
}
}
}
function pruneCacheEntry (
cache: VNodeCache,
key: string,
keys: Array<string>,
current?: VNode
) {
const cached = cache[key]
if (cached && (!current || cached.tag !== current.tag)) {
cached.componentInstance.$destroy()
}
cache[key] = null
remove(keys, key)
}
问题一:
数据污染问题,当不同组件中都含有同一个input查询,就会数据污染
原因:
<router-view :key="$route.path" />
没有设置 key
由于组件名称相同,所以只创建了一个组件实例,vue 会复用相同的组件,如果路由有多个子路由,当在子路由来回切换时,会导致页面不刷新,这是因为不在执行created和mounted这些钩子函数(可以通过watch来监听$route的变化从而实现加载不同的组件。)
解决:
给<router-view :key="$route.path" />
加上唯一key。
-
设置 key 属性值为 $route.path
/detail/1 => /detail/2 (路由内配置path: 'detail/:id')
由于这两个路由的$route.path不一样, 所以组件被强制不复用, 相关钩子加载顺序为:
beforeRouteUpdate => created => mounted/detail?id=1 => /detail?id=2,
由于这两个路由的$route.path一样, 所以和没设置 key 属性一样, 会复用组件, 相关钩子加载顺序为: beforeRouteUpdate
-
设置 key 属性值为 $route.fullPath
/detail/1 => /detail/2 由于这两个路由的$route.fullPath不一样, 所以组件被强制不复用, 相关钩子加载顺序为: beforeRouteUpdate => created => mounted /detail?id=1 => /detail?id=2 由于这两个路由的$route.fullPath不一样, 所以组件被强制不复用, 相关钩子加载顺序为: beforeRouteUpdate => created => mounted
加上key的注意事项:
● 问题:
有key的router-view可能会创建出多余的组件实例,导致内存泄漏。
● 产生原因:
新的路由导航结束时,如果这个有key的router-view未被激活(通常这种情况会发生在有key的router-view层级较深,而当前路由层级较浅),则这个router-view依然会以当前的新key创建一个组件实例(所创建的组件实例为此router-view最后一次渲染的组件)
● 解决方案:
限制router-view所绑定key的值的区间为所有可激活此router-view的路由的path。
● 示例代码:
<keep-alive>
<router-view :key="routeKey" />
</keep-alive>
---分割线---
data(){
return {
currentRoute: ''
}
},
computed:{
routeKey(){
if(this.$route.path.startsWith('/insight/')){
this.currentRoute= this.$route.path
return this.$route.path
}else{
return this.currentRoute
}
}
},
问题二:
动态路由页面,同时打开多个详情页(例:路由为/detail/:id的两个详情页/detail/1, /detail/2),当关闭/detail/1标签页时,/detail/2的页面缓存也会被清除。
不同路由共用同一组件时(如详情页路由fullPath分别是/detail/1, /detail/2组件都是detail.vue),组件是相同的,组件名也是相同的。所以缓存清除时是一块清除的。当删除一个详情页的缓存,其他打开的详情页也会被清除。如果不删除,点击刚才那条列表数据还是取的缓存中的值。
可能有人会想,既然组件会被复用,组件名一致,那直接将include内的组件名换成路由path不就好了吗?但是这样是不行的,会导致本该被缓存的页面没有被缓存到,因此需要重新考虑可行的方案。
解决方式:
- 通过动态改变组件名来使相同组件在不同路由下使用不同组件名。
- 更改keep-alive源码使自定义key为path,根据页面路由判断缓存
- 本文主要通过更改源码,使用自定义keep-alive来达到目的。
解决:
1、重写的keep-alive源码:
/**
- 重写 keep-alive 源码,
- 使 include 可以按照路由地址path匹配,而不是按照组件的 name 匹配。
*/
const _toString = Object.prototype.toString;
function isDef(v) {
return v !== undefined && v !== null;
}
function isRegExp(v) {
return _toString.call(v) === "[object RegExp]";
}
function getComponentName(opts) {
//return opts && (opts.Ctor.options.name || opts.tag)
return this.$route.path;
}
function isAsyncPlaceholder(node) {
return node.isComment && node.asyncFactory
}
function getFirstComponentChild(children) {
if (Array.isArray(children)) {
for (let i = 0; i < children.length; i++) {
const c = children[i];
if (isDef(c) && (isDef(c.componentOptions) || isAsyncPlaceholder(c))) {
return c;
}
}
}
}
function matches(pattern, name) {
if (Array.isArray(pattern)) {
return pattern.indexOf(name) > -1;
} else if (typeof pattern === "string") {
return pattern.split(",").indexOf(name) > -1;
} else if (isRegExp(pattern)) {
return pattern.test(name);
}
/* istanbul ignore next */
return false;
}
function pruneCache(keepAliveInstance, filter) {
const { cache, keys, _vnode } = keepAliveInstance;
for (const key in cache) {
const cachedNode = cache[key];
if (!cachedNode) {
// 之前默认从router-view取储存key值, 现在改为路由name, 所以这里得改成当前key
// const name = getComponentName.call(keepAliveInstance, cachedNode.componentOptions)
const name = key;
if (name && filter(name)) {
pruneCacheEntry(cache, key, keys, _vnode);
}
}
}
}
function remove(arr, item) {
if (arr.length) {
const index = arr.indexOf(item);
if (index > -1) {
return arr.splice(index, 1);
}
}
}
function pruneCacheEntry(cache, key, keys, current) {
const cached = cache[key];
if ((cached && !current) || cache.tag !== current.tag) {
cached.componentInstance.$destroy();
}
cache[key] = null;
remove(keys, key);
}
const patternTypes = [String, RegExp, Array];
export default {
name: "keep-alive-self",
abstract: true,
props: {
include: patternTypes,
exclude: patternTypes,
max: [String, Number],
},
created() {
this.cache = Object.create(null);
this.keys = [];
},
destroyed() {
for (const key of this.cache) {
pruneCacheEntry(this.cache, key, this.keys);
}
},
mounted() {
this.$watch("include", (val) => {
pruneCache(this, (name) => matches(val, name));
});
this.$watch("exclude", (val) => {
pruneCache(this, (name) => !matches(val, name));
});
},
render(h) {
const slot = this.$slots.default;
const vnode = getFirstComponentChild(slot);
const componentOptions = vnode && vnode.componentOptions;
if (componentOptions) {
// check pattern
const name = getComponentName.call(this, componentOptions);
//对于没有name值得设置为路由得name, 支持vue-devtool组件名称显示
if (!componentOptions.Ctor.options.name) {
vnode.componentOptions.Ctor.options.name;
}
const { include, exclude } = this;
if (
// not included
(include && (!name || !matches(include, name))) ||
// excluded
(exclude && name && matches(exclude, name))
) {
return vnode;
}
const { cache, keys } = this;
// 储存的key值, 默认从router-view设置的key中获取
// const key = vnode.key == null
// ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
// : vnode.key
// 2. 储存的key值设置为路由中得name值
const key = name;
if (cache[key]) {
vnode.componentInstance = cache[key].componentInstance;
remove(keys, key);
keys.push(key);
} else {
cache[key] = vnode;
keys.push(key);
if (this.max && keys.length > parseInt(this.max)) {
pruneCacheEntry(cache, keys[0], keys, this._vnode);
}
}
vnode.data.keepAlive = true;
}
return vnode || (slot && slot[0]);
},
};
2、注册全局组件:在 main.js 中引入自定义 keep-alive 组件——BaseKeepAlive
// main.js 文件添加以下代码
import BaseKeepAlive from '@/utils/base/KeepAlive'
Vue.component('BaseKeepAlive', BaseKeepAlive)
3、把原 keep-alive 替换为自定义 BaseKeepAlive (若依系统在AppMain.vue文件内)
<BaseKeepAlive :include="cachedViews">
<router-view :key="$route.path" />
</BaseKeepAlive>
参考:
https://blog.csdn.net/m0_60692814/article/details/125564038
https://blog.csdn.net/qq_44170108/article/details/133313641
https://blog.csdn.net/JackieDYH/article/details/115555330