vite+vue3动态添加路由,提示找不到路径
Vue version
3.2.38
Link to minimal reproduction
Steps to reproduce
`import { createRouter, createWebHashHistory } from 'vue-router' import { message } from 'ant-design-vue'; import Nprogress from 'nprogress'; import 'nprogress/nprogress.css'; import { menu } from '@/api/auth';
const modules = import.meta.glob('/src/views//.vue'); // Vite 支持使用特殊的 import.meta.glob 函数从文件系统导入多个模块
const router = createRouter({ history: createWebHashHistory(import.meta.env.BASE_URL), routes: [ { path: '/login', name: 'login', component: modules['/src/views/login/IndexView.vue'], meta: { login: true } }, // { // component: modules['/src/views/layout/IndexView.vue'], // children: [ // { // path: '/', // component: modules['/src/views/home/IndexView.vue'], // name: 'home-list', // meta: { title: '基本信息' }, // }, // ], // }, ] });
// 递归引入路由
const dynamicRouter = routers => {
const list = [];
routers.map((item, index) => {
list.push({
component: modules['/src/views/layout/IndexView.vue'],
children: [
{
path: item.path,
name: item.unique_auth,
// component: () => import(@/views/${item.component}.vue
),
component: modules[/src/views/${item.component}.vue
],
meta: { title: item.name }
}
],
});
if (item.children && item.children.length) {
list[index].children.children = dynamicRouter(item.children);
}
});
return list;
};
// 挂载全局前置路由守卫 router.beforeEach(async (to, from, next) => { Nprogress.start(); document.title = to.meta.title === undefined ? '后台管理系统' : to.meta.title; if (to.name == 'login') { next(); return; } if (localStorage.getItem('Authori-zation')) { if (to.name == 'login') { next('/'); Nprogress.done(); } else { // 从后端获取路由 // const { data } = await menu({type:1, show: 1}); // dynamicRouter(data.menu).map(item => { // router.addRoute(item); // });
// 写死路由
router.addRoute({
component: modules['/src/views/layout/IndexView.vue'],
children: [
{
path: '/',
component: modules['/src/views/home/IndexView.vue'],
name: 'Home',
meta: { title: '基本信息' },
},
],
});
// next({ ...to, replace: true });
}
} else { next({ name: 'login' }); Nprogress.done(); } });
// 挂在全局后置路由 router.afterEach(() => { Nprogress.done(); });
export default router `
What is expected?
动态添加路由
What is actually happening?
[Vue Router warn]: No match found for location with path "/". [Vue Router warn]: Detected an infinite redirection in a navigation guard when going from "/" to "/". Aborting to avoid a Stack Overflow. This will break in production if not fixed. [Vue Router warn]: Unexpected error when starting the router: Error: Infinite redirect in navigation guard.
System Info
No response
Any additional comments?
在路由守卫里当动态添加路由,无论是从后端获取路由参数,还是写死,总是添加不了,提示不存在路径,求教解决办法,应该怎么写
The issue list is reserved exclusively for bug reports and feature requests. That means we do not accept usage questions.
For usage questions, please use the following resources:
- Read the docs
- Watch video tutorials
- Ask on the forums
- Ask on the chat
- Look for / ask questions on Stack Overflow