Vue3.0+ts+vite动态路由配置

  1. 后台返回数据
const menuList: object = [
    {
        "id": 1000,
        "parentId": 0,
        "icon": "AppleFilled",
        "name": "组织架构",
        "path": "",
        "component": "Layout",
        "redirect": null,
        "type": "0",
        "children": [{
            "id": 1100,
            "parentId": 1000,
            "children": [],
            "icon": "ToolFilled",
            "name": "用户管理",
            "path": "/Organization/user",
            "component": "views/Organization/user/index",
            "redirect": null,
            "type": "0",
        },
            {
                "id": 1200,
                "parentId": 1000,
                "children": [],
                "icon": "ToolFilled",
                "name": "部门管理",
                "path": "/Organization/department",
                "component": "views/Organization/department/index",
                "redirect": null,
                "type": "0",
            }]
       }]

路由基本安装这儿就不讲了,不会自己百度,都很简单
2. router文件夹结构
在这里插 router文件夹结构入图片描述
3. 创建静态路由(staticRouter.ts)

 const  staticRouter =[
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/Login/index.vue'),
    },
    {
        path: '/404',
        name: '404',
        component: () => import('@/views/other/404.vue'),
    },
]
export  default  staticRouter
  1. 动态路由主入口(MainRouter.ts)
 const MainRouter = [
    {
        path: '/',
        name: 'main',
        component: () => import('@/Layout/Main.vue'),
        redirect: { name: 'home' },
        meta: { title: "首页" },
        children: [
            {
                name: 'home',
                path: '/home',
                component: () => import('@/views/Home/index.vue'),
            }
        ],
    },
]
export  default  MainRouter
  1. 创建index.ts文件,开始路由配置
 import { createRouter, createWebHistory } from 'vue-router'
const routerHistory = createWebHistory()
import NProgress from 'nprogress' // 加载进度条
import 'nprogress/nprogress.css'
import staticRouter from './staticRouter' // 独立页面
import MainRouter from './MainRouter' //模块路由(基于主入口布局页面)
import useStore from '@/store' //使用vuex
import * as user from "@/api/user"; //请求api,获取菜单
import Main from '@/Layout/Main.vue' // 导入动态路由父路由
import {isURL} from '@/utils/validate'  //根据自己情况使用,主要判断是不是一个以https||http开头的链接
const router = createRouter({
    history: routerHistory, //路由模式
    routes: [
        ...staticRouter,  //注册静态路由
        ...MainRouter //注册动态路由入住路由
    ]
})


// 格式化路由 //将后台返回的路由注册到router中(根据自己后台返回结构数据自己定义,仅做参考)
export function formatRouter(data: []) {
    return data.map((item: any) => {
        let i = 0
        const route = {
            name: item.path || `l-${item.id}`,
            path: '',
            component: '',
            meta: {
                title: item.name,
                iframeURL: '',
                icon: item.icon,
                level: i += 1
            },
            redirect: '',
            children: []
        } as any
        if (isURL(item.path)) {
            route['name'] = 'iframeURL-' + item.id
            route['path'] = item.path
            route['meta']['iframeURL'] = item.path
        }else {
            route['path'] = item.path === '' ? `/l-${item.id}` : item.path
            route['component'] = item.path === '' ? Main : () => import(`../${item.component}.vue`)
            route['isMain'] = item.path === '' ? false : true
        }
        if (item.children && item.children.length > 0) {
            route.children = formatRouter(item.children)
        }
        return route
    })
}
router.beforeEach((to, from, next) => {
    // 开启进度条
    NProgress.start()
    //解决子路由刷新出现空白
    if (useStore.getters.permissions.length === 0) {
        user.getList().then((res:any)=>{
            const  Router = formatRouter(res)
            useStore.commit('SET_PERMISSIONS',Router)
            console.log(Router);
            Router.forEach(item => {
               if (item.isMain){
                   router.addRoute('main',item)
               }else {
                   router.addRoute(item)
               }
            })
            // 如果 addRoute 并未完成,路由守卫会一层一层的执行执行,直到 addRoute 完成,找到对应的路由
            next({ ...to, replace: true })
        })
    } else {
        next()
    }
})
router.afterEach((to,from) => {
    // 关闭进度条
    NProgress.done()
})
export default router
  1. 将路由挂在到app上
import { createApp } from 'vue'
import App from '@/App.vue'
import "@/index.css";
import router from '@/router'
const  app =createApp(App)
import store from '@/store'
import * as Icons from "@ant-design/icons-vue";
// import ElementPlus from 'element-plus'

// app.config.globalProperties.vueEvent = vueEvent
// app.use(ElementPlus, { size: 'small', zIndex: 3000 })
//挂在
app.use(store)
app.use(router)
const data:any = Icons
for (const i in data) {
    app.component(i, data[i]);
}
app.mount('#app')
  • 1
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值