vue3 + ts + vite + pinia 封装动态路由

我这个是纯前端的 目前项目在搭建阶段 所以可能有些不足 希望能给大伙带来一点参考

老规矩 直接上代码

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值