1. 组件设置 name
核心:keep-alive 只认组件 name,所以 cachedViews 或 include 必须用组件 name,而不是路由 name。
1. defineComponent模式
ts
<script lang="ts">
import { defineComponent} from 'vue';
export default defineComponent({
name: 'CustomName'
})
</script>
2. setup语法糖
需要单独新增一个script标签
ts
// 页面为 TSX 时,需将 <script> 标签改为 lang="tsx"
<script lang="ts">
export default {
name: 'CustomName',
inheritAttrs: false,
customOptions: {}
}
</script>
3. 借助插件
2. 动态生成组件 name 的实践方案
相较于前端存储全量路由结合接口权限过滤的方案,此方案借助 Vue2 createCustomComponent 的思路:
- 每条路由都会生成一个独立的组件对象,并为其分配唯一的
name - 在动态生成组件时,将组件的
name设置为基于路由path处理后的安全名称
1. createCustomComponent
ts
import { defineAsyncComponent, defineComponent, h } from "vue";
/**
* @param { String } name 组件自定义名称
* @param { Component | Promise<Component> } componentPromise
* @return { Component }
*/
export function createCustomComponent(name: string, componentPromise: any) {
// 1. 将 Promise 包装成标准的异步组件
const AsyncComp = defineAsyncComponent({
loader: () =>
componentPromise instanceof Promise ? componentPromise : Promise.resolve(componentPromise),
// 如果需要,可以在这里配置 loadingComponent
});
return defineComponent({
name, // 必须设置,用于匹配 keep-alive 的 include
setup() {
// 2. 直接返回渲染函数,渲染异步组件
// 移除外层的 div,让 AsyncComp 成为 KeepAlive 的直接子级
return () => h(AsyncComp);
},
});
}
2. 组件名转化
ts
// 将 path 转成合法的组件名,避免 '/' 等字符
function genComponentNameByPath(path: string) {
return path.replace(/\//g, "_").replace(/^_/, "");
}
3. 路由接入示例
ts
component: () => import("@/views/dashboard/index.vue")
// 调整为
component: createCustomComponent("Dashboard", import("@/views/dashboard/index.vue"))
3. 通用组件缓存策略
疑问:如果共用一个组件来进行创建、编辑、详情,怎么根据路径进行匹配?
假设路径是:/banner-list/banner-create、/banner-list/banner-edit、/banner-list/banner-detail 需要先进行路径命中匹配,无法命中则直接进行默认匹配:
- 先解析上层路径,找到文件所在位置
- 再进行精准匹配,比如:公共组件统一命名为:basic-component
ts
// 扫描views目录下的vue文件
const modules = import.meta.glob("@/views/**/**.vue");
// 全局需要 keepAlive 的 path 列表
const pathKeepAliveList: string[] = [];
/**
* 解析后端返回的路由数据
* @param rawRoutes 后端返回的原始路由数据
* @returns 解析后的路由配置数组
*/
const parseDynamicRoutes = (rawRoutes: AsyncRouter[]): RouteRecordRaw[] => {
const parsedRoutes: RouteRecordRaw[] = [];
rawRoutes.forEach(item => {
const childrenColumn: RouteRecordRaw = {
path: item.path,
name: item.name,
component: Layout,
meta: {
title: item.name,
icon: item.icon,
},
children: [] as RouteRecordRaw[],
};
if (item.children?.length) {
childrenColumn.redirect = item.children[0].path;
item.children.forEach(v => {
childrenColumn.children.push({
path: v.path,
name: v.path,
meta: {
title: v.name,
// 满足条件的path开启 keepAlive
keepAlive: pathKeepAliveList.includes(v.path),
// 取二级路由为高亮,兼容二、三级路由匹配
activeMenu: v.path.match(/^/[^/]+/[^/]+/)?.[0],
},
component: createCustomComponent(v.path, modules[`/src/views${v.path}/index.vue`]),
});
});
}
parsedRoutes.push(childrenColumn);
});
return parsedRoutes;
};