vue-router 登录拦截(前置)、动态注册路由、路由缓存。
npm i vue-router admin-router-plus --save
- initRouter(options: RouterConfig): Router; 初始化 Router
- router: Router; Router 实例
- clearRoutes(): void; 清除动态路由
- getMenu(key: string, parentKey?: string | undefined): any; 获取动态路由
export declare interface RouterConfig {
routes: RouteRecordRaw[]; // 静态路由列表
modules?: Record<string, any>; // 导入所有动态页面文件
enableDynamic?: boolean, // 是否开启动态路由
routesRequest?: () => Promise<DynamicRoute[]>; // 动态路由请求
routesFormat?: Record<string, string>; // 动态路由字段映射关系(接口字段:路由字段)
routesModules?: Record<string, any>; // 动态路由必备组件(Layout/Empty)
}
export declare interface DynamicRoute {
parent?: string; // 挂载父级(父级name属性值,0或空为顶级路由)
path: string; // 路由地址
name: string; // 路由名称
redirect?: string; // 路由重定向(name属性)
component: string; // 页面组件(文件名)
hiddenMenu?: boolean; // 是否在菜单栏中隐藏
title?: string; // Mete:标题
icon?: string; // Mete:图标
noAuth?: boolean; // Mete:是否免登录(动态路由注册必须登录)
noCache?: boolean; // Mete:是否禁用缓存
activeMenu?: string; // Mete:自定义激活菜单(name属性)
isDynamic?: boolean; // Mete: 动态路由添加标识(自动)
children?: DynamicRoute[]; // 子路由
}
main.ts
import { createApp } from "vue";
import App from "./App.vue";
import { routerPlus } from "admin-router-plus";
import routes from "./router";
const Empty = () => import("admin-router-plus/lib/layout/Empty.vue");
const Layout = () => import("admin-router-plus/lib/layout/Layout.vue");
const app = createApp(App);
app.use(routerPlus, {
routes: routes, // [必填]静态路由列表
enableDynamic: true, // [可选]开启动态路由
modules: import.meta.glob(`./views/**`), // [可选]引入所有页面文件
routesRequest: async () => {
const res = await getJSON("/menus");
return res.data;
}, // 动态路由请求接口(跳转鉴权路由触发)
routeFormat: { menuName: "title", menuIcon: "icon", loadRes: "path" }, // 字段映射关系
routesModules: { Empty, Layout }, // 动态路由必备组件(Layout/Empty)
});
app.mount("#app");
router.ts
export default [
{
path: "/",
name: "home",
meta: { title: "首页" },
component: () => import("../views/HomeView.vue"),
},
{
path: "/login",
name: "login", // 约定:未授权页面跳转 { name: 'login' }
meta: { noCache: true, noAuth: true },
component: () => import("../views/LoginView.vue"),
},
{
path: "/about",
name: "about",
meta: {},
component: () => import("../views/AboutView.vue"),
},
];
App.vue
<template>
<!-- <el-config-provider :locale="locale"> -->
<router-view v-slot="{ Component }">
<!-- 在 3.2.34 或以上的版本中,使用 <script setup> 的单文件组件会自动根据文件名生成对应的 name 选项,无需再手动声明。 -->
<keep-alive>
<component
:is="Component"
:key="$route.name"
v-if="!$route.meta.noCache"
/>
</keep-alive>
<component :is="Component" :key="$route.name" v-if="$route.meta.noCache" />
</router-view>
<!-- </el-config-provider> -->
</template>
<script setup lang="ts">
import "element-plus/dist/index.css";
</script>
<style scoped></style>