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
    评论
Vue 3 中使用 TypeScript 并结合 Vite 构建工具来配置路由,可以按照以下步骤进行操作: 1. 首先,确保你已经创建了一个 Vue 3 项目,并且已经安装了相关依赖。可以通过以下命令创建一个新的 Vue 3 项目: ``` $ npm init vite@latest my-vue3-app --template vue-ts $ cd my-vue3-app $ npm install ``` 2. 安装 Vue Router 和相关 TypeScript 类型定义: ``` $ npm install vue-router@next $ npm install @types/vue-router ``` 3. 在 `src` 目录下创建一个新的文件夹,比如 `router`,并在其中创建一个名为 `index.ts` 的文件,用于配置路由。 4. 在 `index.ts` 文件中,首先引入 Vue Router 和相关组件: ```typescript import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'; import Home from '../views/Home.vue'; import About from '../views/About.vue'; ``` 5. 声明一个 `routes` 数组,用于定义路由配置: ```typescript const routes: Array<RouteRecordRaw> = [ { path: '/', name: 'Home', component: Home, }, { path: '/about', name: 'About', component: About, }, ]; ``` 在这个例子中,我们定义了两个路由:`'/'` 对应到 `Home` 组件,`'/about'` 对应到 `About` 组件。 6. 创建一个路由实例,并且将路由配置传递给它: ```typescript const router = createRouter({ history: createWebHistory(), routes, }); ``` 这里使用了 `createWebHistory()` 来创建一个基于 HTML5 History API 的路由模式。 7. 最后,将路由实例导出,以便在 Vue 应用中使用: ```typescript

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值