路由router
一、安装路由
npm install vue-router@4
二、注册路由
-
在项目
src/router目录下创建index.ts文件: -
在
index.ts中:// router/index.ts import type { App } from 'vue' import { createRouter, createWebHistory, type Router, type RouteRecordRaw } from 'vue-router' /** 引入modules目录下的所有.ts模块 */ const modules: Record<string, any> = import.meta.glob('./modules/*.ts', { eager: true }) console.log(modules) /** 所有模块暴露的路由配置 */ const routeList: RouteRecordRaw[] = [] /** 遍历moduls的所有key拿到所有模块暴露的内容 */ Object.keys(modules).forEach((key) => { routeList.push(...modules[key].default) }) console.log('routeList', routeList) /** 存放路由的列表 */ const routes: RouteRecordRaw[] = [] /** 创建路由实例对象 */ const router: Router = createRouter({ history: createWebHistory(), // 路由的模式,这里是history模式 routes: routes.concat(routeList) // 路由列表 }) /** 注册路由实例对象 */ export function setupRouter(app: App): void { app.use(router) } /** 向外暴露路由实例对象 */ export default router -
创建
router/router.type.d.ts文件,它的作用是用来声明路由的格式以及其他路由模块用到的规则:// router.type.d.ts import type { Component, VNode } from 'vue' /** 路由格式 */ export interface DDRouteRecordRaw { /** 路由地址 */ path: string /** 路由名称 */ name?: string /** 路由地址对应的组件 */ component?: Component /** 路由重定向 */ redirect?: string /** 路由元信息 */ meta?: { /** 侧边栏菜单标题 */ title?: string /** 侧边栏菜单图标 */ icon?: VNode | string /** 侧边栏中的排序---只有顶级菜单才有 */ sort?: number /** 是否显示在侧边栏中 */ sidebarVisibility?: boolean } /** 子路由 */ children?: DDChildrenRouteRecordRaw[] } /** 子路由格式 */ export interface DDChildrenRouteRecordRaw { /** 路由地址 */ path: string /** 路由名称 */ name?: string /** 路由地址对应的组件 */ component?: Component /** 路由元信息 */ meta: { /** 侧边栏菜单标题 */ title?: string /** 侧边栏菜单图标 */ icon?: VNode | string /** 页面权限 */ roles?: string /** 按钮级别权限 */ auths?: string } /** 子路由 */ children?: DDChildrenRouteRecordRaw[] } -
创建
modules目录,它是用来存放各个模块的路由配置:import type { DDRouteRecordRaw } from '../router.type' /** 地图模块路由配置 */ const routes: DDRouteRecordRaw[] = [ { path: '/map', redirect: '/map/index', meta: { sort: 0, title: '地图', icon: '', sidebarVisibility: false }, children: [ { path: 'index', name: 'Map', component: () => import('@/views/map/index.vue'), meta: { title: '地图', icon: '' } } ] } ] export default routes -
App.vue:
<template> <div class="app"> <router-view></router-view> </div> </template> <script setup lang="ts"> defineOptions({ name: 'App' }) </script> <style lang="scss" scoped> .app { background-color: $color; } </style>