vue3+vite注册动态路由的实践
目的是先将从后端拿到返回的路由列表的component与本地的路径进行比对,然后将匹配的数据拿到后再渲染,注意,使用动态路由注册后的路由需要走一次replace,否则将无法渲染
// route/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
// const comp = () => import ('../views/AboutView.vue' )
// console.log('comp :>> ', await comp()?.default)
const baseRoute = [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
component: () => import('../views/AboutView.vue')
}
]
console.log('baseRoute :>> ', baseRoute );
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: baseRoute
})
const page = import.meta.glob('../views/**/*.vue', { eager: true })
const cru = Object.entries(page)
// 递归添加路由
const loadRoute = (list) => {
list.forEach((item) => {
const path = item.site // size:后端配置好的路由地址
console.log('path :>> ', path);
cru.forEach( async cruItem => {
// cruItem是一个二维数组
if (cruItem[0] === path) {
// 注意:异步渲染,需要走await才能返回读取后的组件数据
item.component = await cruItem[1]?.default
console.log('cruItem[1] :>> ', cruItem[1]);
console.log('11111 :>> ', 11111);
console.log('path :>> ', path);
console.log('11111 :>> ', 11111)
}
})
router.addRoute(item)
if (item.children) {
loadRoute(item.children)
}
})
}
console.log('page :>> ', page);
const asyncRoute = [
{
path: '/layout',
name: 'layout',
site: '../views/Layout.vue',
redirect: '/demo1',
component: () => import('../views/Layout.vue'),
children: [
{
path: '/demo1',
name: 'demo1',
site: '../views/Demo1.vue',
component: () => import('../views/Demo2.vue')
},
{
path: '/test1',
name: 'test1',
site: '../views/test/test1.vue',
component: () => import('../views/text/test1.vue')
},
{
path: '/test2',
name: 'test2',
site: '../views/test/test2.vue',
component: () => import('../views/test/test2.vue')
}
]
}
]
router.beforeEach((to, from, next) => {
if (!router.hasRoute('layout')) {
loadRoute(asyncRoute)
// console.log('asyncRoute :>> ', asyncRoute);
router.replace({...to,replace:true})
}
console.log('router.getRoutes() :>> ', router.getRoutes())
next()
})
export default router