vue3+vite做动态路由时,得到的component格式总是不正确如下图所示
第一个是router中添加的,第二个是在页面中动态路由添加的,代码如下
router/index.ts
// import VueRouter from 'vue-router'
import {createRouter, createWebHashHistory} from 'vue-router'
const routes:any = [
{
path: '/',
name: '/',
redirect: 'Login'
},
{
path: '/login',
name: 'Login',
component: () => import( '../views/login/Login.vue')
},
// {
// path: '/home',
// name: 'Home',
// component: () => import( '../views/home/Home.vue')
// },
{
path: '/home',
name: 'Home',
redirect: 'homeIndex',
component: () => import( '../views/home/Home.vue'),
children: [
{
path: '/homeIndex',
name: 'HomeIndex',
component: () => import( '../views/home/HomeIndex.vue')
},
]
},
]
// Vue-router新版本中,需要使用createRouter来创建路由
export default createRouter({
// 指定路由的模式,此处使用的是hash模式
history: createWebHashHistory(),
routes // short for `routes: routes`
})
页面中添加路由动态页面代码
const getMenuList = () => {
homeGetMenuListByUserId("").then(function (res) {
// 处理成功情况
console.log(res.data.data);
homeMenuData.menuList = res.data.data
const modules = import.meta.glob('../views/*/*.vue')
for (let i =0;imenuList.length;i++){
for(let j =0;j<(homeMenuData.menuList[i] as any).childrenList.length;j++){
let list: any = (homeMenuData.menuList[i] as any).childrenList[j]
//const viteComponent = import.meta.glob("../views/**/*.vue")
router.addRoute({
path:list.path,
name:list.name,
// component: viteComponent[`../views${list.component}.vue`]
component: () => import(`../views/${list.component}`)
})
}
}
console.log(router.getRoutes());
}).catch(function (error) {
// 处理错误情况
console.log(error);
})
.then(function () {
// 总是会执行
});
}
这个如何解决
望采纳!!点击该回答右侧的“采纳”按钮即可采纳!!我可以猜测你可能是在尝试在Vue.js应用程序中使用动态路由。
我可以猜测你可能是在尝试在Vue.js应用程序中使用动态路由。
如果是这样的话,我猜测你可能是在使用Vite的vue-router插件,而这个插件似乎存在一些问题,导致在使用动态路由时,你得到的组件格式是不正确的。
如果我的猜测是正确的,你可以尝试以下解决方案之一:
在你的路由配置中使用绝对路径,而不是相对路径。例如,你可以使用 { path: '/login', component: '/src/views/login/Login.vue' } 而不是 { path: '/login', component: './src/views/login/Login.vue' }。
尝试使用替代vue-router插件,例如vue-router-next或vue-router-3。
尝试在你的组件中使用具体的渲染函数,而不是使用v-bind动态绑定。例如,你可以使用以下代码:
const Login = {
render() {
return <h1>Hello World!</h1>
}
}
const routes = [
{ path: '/login', component: Login }
]
const router = new VueRouter({
routes
})