# 03. Vue Router 路由
URL: /%E6%96%87%E6%A1%A3/04.%E5%BC%80%E5%8F%91%E6%96%87%E6%A1%A3/01.%20%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91/02.%20%E6%A0%B8%E5%BF%83%E6%8A%80%E6%9C%AF/05.%20Vue%20Router%20%E8%B7%AF%E7%94%B1

Vue Router 4 路由配置与使用指南


# Vue Router 路由

> [!info] 项目使用 Vue Router 4.5.0

## 路由目录结构

```
src/router/
├── index.ts           # 路由主配置
├── router.ts          # Router 实例创建
├── routes/            # 路由配置
│   ├── index.ts       # 路由汇总
│   ├── basic.ts       # 基础路由（登录等）
│   ├── mainOut.ts     # 主路由
│   ├── staticRouter.ts # 静态路由
│   └── modules/       # 业务模块路由
└── guard/             # 路由守卫（注意是 guard 不是 guards）
    ├── index.ts       # 守卫汇总
    ├── permissionGuard.ts   # 权限守卫
    ├── stateGuard.ts        # 状态守卫
    └── paramMenuGuard.ts    # 参数菜单守卫
```

## 基本用法

### 定义路由

```typescript
// src/router/routes/modules/dashboard.ts
import type { AppRouteModule } from '@/router/types';

const dashboard: AppRouteModule = {
  path: '/dashboard',
  name: 'Dashboard',
  component: () => import('@/views/dashboard/index.vue'),
  meta: {
    title: 'Dashboard',
    icon: 'mdi:dashboard',
    hideChildrenInMenu: true,
  },
};

export default dashboard;
```

### 路由跳转

```vue
<script setup lang="ts">
import { useRouter } from 'vue-router';

const router = useRouter();

// 编程式导航
function goHome() {
  router.push('/');
}

function goBack() {
  router.back();
}

// 带参数跳转
function goToUser(id: string) {
  router.push({
    path: '/user/detail',
    query: { id },
  });
}
</script>

<template>
  <!-- 声明式导航 -->
  <router-link to="/">首页</router-link>
  <router-link :to="{ path: '/user', query: { id: 123 } }">用户</router-link>
</template>
```

## 路由模式

### hash 模式

```typescript
import { createRouter, createWebHashHistory } from 'vue-router';

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});
```

- URL 带 `#`，如 `http://example.com/#/about`
- 不需要服务器配置
- 兼容性更好

### history 模式

```typescript
import { createRouter, createWebHistory } from 'vue-router';

const router = createRouter({
  history: createWebHistory(),
  routes,
});
```

- URL 更美观，如 `http://example.com/about`
- 需要服务器配置支持
- SPA 需要配置 fallback

## 路由守卫

### 全局守卫设置

```typescript
// src/router/guard/index.ts
export function setupRouterGuard(router: Router) {
  createPageGuard(router);
  createPageLoadingGuard(router);
  createHttpGuard(router);
  createScrollGuard(router);
  createMessageGuard(router);
  createProgressGuard(router);
  createPermissionGuard(router);
  createParamMenuGuard(router); // must after createPermissionGuard
  createStateGuard(router);
}
```

### 权限守卫

```typescript
// src/router/guard/permissionGuard.ts
import { useUserStore } from '@/store/modules/user';
import { usePermissionStore } from '@/store/modules/permission';

export function createPermissionGuard(router) {
  router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore();
    const permissionStore = usePermissionStore();
    const token = userStore.getToken;

    if (token) {
      if (to.path === '/login') {
        next({ path: '/' });
      } else {
        if (!permissionStore.isDynamicAddedRoute) {
          await permissionStore.buildRoutesAction();
          next({ ...to, replace: true });
        } else {
          next();
        }
      }
    } else {
      if (to.meta.ignoreAuth) {
        next();
      } else {
        next({ path: '/login', query: { redirect: to.fullPath } });
      }
    }
  });
}
```

## 路由元信息

```typescript
declare interface RouteMeta {
  // 标题
  title: string;
  // 图标
  icon?: string;
  // 是否隐藏菜单
  hideMenu?: boolean;
  // 是否忽略权限
  ignoreAuth?: boolean;
  // 是否缓存页面
  keepAlive?: boolean;
  // 外链地址
  frameSrc?: string;
  // 角色权限
  roles?: string[];
  // 是否隐藏子菜单
  hideChildrenInMenu?: boolean;
  // 是否隐藏标签页
  hideTab?: boolean;
}
```

## 动态路由

项目支持从后端加载路由配置：

```typescript
// src/store/modules/permission.ts
async buildRoutesAction() {
  const { getPermMenuList } = useUserStore();
  const routes = await getPermMenuList();

  // 后端路由转换
  const backendRoutes = transformBackendRoutes(routes);

  // 动态添加路由
  backendRoutes.forEach((route) => {
    router.addRoute(route as unknown as RouteRecordRaw);
  });

  this.setDynamicAddedRoute(true);
}
```

## 路由缓存

使用 `<keep-alive>` 缓存组件：

```vue
<template>
  <router-view v-slot="{ Component }">
    <keep-alive :include="getCachedComponents">
      <component :is="Component" :key="route.path" />
    </keep-alive>
  </router-view>
</template>

<script setup lang="ts">
import { useAppStore } from '@/store/modules/app';

const appStore = useAppStore();
const getCachedComponents = computed(() => appStore.getOpenCachedComponents);
</script>
```

## 常用场景

### 获取路由参数

```typescript
import { useRoute } from 'vue-router';

const route = useRoute();

// query 参数
const id = route.query.id;

// params 参数
const userId = route.params.userId;
```

### 监听路由变化

```typescript
import { watch } from 'vue';
import { useRoute } from 'vue-router';

const route = useRoute();

watch(
  () => route.path,
  (newPath) => {
    console.log('路由变化:', newPath);
  }
);
```

### 刷新当前路由

```typescript
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();

function reload() {
  router.replace({
    path: route.redirectedFrom?.path || route.fullPath,
  });
}
```

## 相关链接

- [Vue Router 官方文档](https://router.vuejs.org/)
