Vue3 动态路由下的 KeepAlive 设计方案

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. 借助插件

vue-macros 插件

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;
};
相关推荐
困惑阿三2 小时前
2025 前端技术全景图:从“夯”到“拉”排行榜
前端·javascript·程序人生·react.js·vue·学习方法
苏瞳儿2 小时前
vue2与vue3的区别
前端·javascript·vue.js
weibkreuz4 小时前
收集表单数据@10
开发语言·前端·javascript
hboot4 小时前
别再被 TS 类型冲突折磨了!一文搞懂类型合并规则
前端·typescript
在西安放羊的牛油果4 小时前
浅谈 import.meta.env 和 process.env 的区别
前端·vue.js·node.js
鹏北海4 小时前
从弹窗变胖到 npm 依赖管理:一次完整的问题排查记录
前端·npm·node.js
布列瑟农的星空4 小时前
js中的using声明
前端
薛定谔的猫24 小时前
Cursor 系列(2):使用心得
前端·ai编程·cursor
用户904706683574 小时前
后端问前端:我的接口请求花了多少秒?为啥那么慢,是你慢还是我慢?
前端
深念Y4 小时前
仿B站项目 前端 4 首页 顶层导航栏
前端·vue·ai编程·导航栏·bilibili·ai开发