我这个是纯前端的 目前项目在搭建阶段 所以可能有些不足 希望能给大伙带来一点参考
老规矩 直接上代码
router/indnex.ts
注意,这个是无 # 号路由模式
lStorage:封装一个浏览器缓存方法 同等于 localStorage,set 等价于 setItem,get 等价于 getItem
SYSTEM_ROUTES:全局路由,存储浏览器缓存用的
getRoutes:模拟接口获取需要注入的路由数据
import {
RouteRecordRaw,
createRouter,
createWebHistory, // 使用HTML5 History API,无'#'
// createWebHashHistory, // 用于不支持HTML5 History API的环境,带'#'
} from 'vue-router'
import {
getRoutes } from '@/api/test'
import {
store } from '@/store/index'
import {
lStorage } from '@/utils/storage'
// 全局布局导入
const Layout = () =>
import(/* webpackChunkName: "layout" */ '@/page/layout/index.vue').then(
(m) => m.default
)
// 静态路由表 - 确保每个路由对象遵循正确的类型定义
const staticRoutes: RouteRecordRaw[] = [
// 对于重定向路由,明确指定redirect属性
{
path: '/',
redirect: '/home',
},
{
path: '/404',
component: () => import('@/page/error/404.vue'),
meta: {
hidden: true, title: '404' },
},
{
path: '/:catchAll(.*)', // 不识别的path自动匹配404
redirect: '/404',
},
// 对于常规路由,不包含redirect属性
{
path: '/login',
component: () => import('@/page/login/index.vue'),
meta: {
hidden: true, title: '登录' },
},
]
// 带有布局的子路由
const childRoutes = [
{
path: '/home',
name: 'home',
component: () => import('@/views/home/index.vue'),
meta: {
hidden: false, // 是否隐藏路由
title: '首页', // 标题
keepAlive: true, // 是否缓存路由组件
icon: 'dashboard', // 图标
hasPerm: ['viewHome'], // 权限
},
},
]
// 合并静态路由和带布局的子路由
const routes = [
...staticRoutes,
{
path: '/', component: Layout, name: 'layout', children: childRoutes },
]
// 路由守卫
router.beforeEach(async (to, from, next) => {
let res = null
// 注入动态路由 判断是否被刷新过
if (
Array.isArray(store.routes().routes) &&
store.routes().routes.length === 0
) {
// 如果本地有记录
if (Array.isArray(lStorage.get('SYSTEM_ROUTES'))) {
res = lStorage.get