Vite+vue3+Router4 在事件中添加子路由,切换到添加的子路由,会提示警告,切换到其他路由就报错?
使用vite4+vue3+Router4,测试动态子路由,也就是在事件中,添加子路由,通过类似router.addRoute('admin', { path: 'settings', component: AdminSettings })的代码形式添加动态子路由
涉及的vue页面
<template>
<div class="box">
<div class="header">
<div class="title"><button @click="testClick()">测试</button></div>
<el-radio-group
v-model="radio1"
@change="radio_onchange"
>
<el-radio-button
v-for="(item, index) in page_list"
:key="item.path"
:label="item.path"
>{{ item.label }}</el-radio-button
>
</el-radio-group>
</div>
<div class="content5">
<router-view />
<!-- <router-view v-slot="{ Component }">
<keep-alive>
<component :is="Component" />
</keep-alive>
</router-view> -->
</div>
<div>123</div>
</div>
</template>
<script>
import {asyncRouterMap} from "@/config/router/dyRouter/testRoutes.js"
export default {
data() {
return {
radio1: "",
parentPath:undefined,
PageName:"testHead",
page_list: [
],
};
},
created(){
this.loadHeadRoute();
},
methods: {
loadHeadRoute(){
var head=this.$router.options.routes.find((r)=>r.name===this.PageName)
this.parentPath=head.path;
//this.headerRoute= this.$router.getRoutes().find((r)=>r.name==="testHead");
for(var item of head.children){
this.page_list.push({path:head.path+"/"+item.path,label:item.title});
}
this.radio1=this.page_list[0].path;
this.switchChildPage(this.page_list[0]);
},
testClick(){
for(var item of asyncRouterMap){
this.page_list.push({path:this.parentPath+"/"+item.path,label:item.title});
this.$router.addRoute(this.PageName,item)
}
console.log(this.$router.getRoutes());
},
radio_onchange(value) {
var item = this.page_list.find((item) => item.path ===value);
this.switchChildPage(item);
},
switchChildPage(item){
this.$router.push(item.path);
}
},
};
</script>
静态路由配置:
import { createRouter, createWebHashHistory } from 'vue-router'
var router=createRouter({
history: createWebHashHistory(),
routes: [
{ path: '/test',page_id:1, component: ()=>import('@/views/begin/test/testIndex.vue'),
},
{ path: '/test1',name:"testHead", component: ()=>import('@/views/begin/test/AdminIndex.vue'),
children:[
{path:"test1",title:"测试1",component:()=>import('@/views/header/testHead1.vue')},
{path:"test2",title:"测试2",component:()=>import('@/views/header/testHead2.vue')},
],
},
{ path: '/testFail',page_id:1, component: ()=>import('@/views/errorPage/Fail404.vue'),
},
{ path: '/:catchAll(.*)',
redirect:"/testFail"
},
]
});
export default router
动态路由配置:
export const asyncRouterMap=[
{
path: 'test3',
title:"测试3",
component: () => ()=>import('@/views/header/testHead3.vue'),
}
]
截图:演示动图:。
点击按钮,添加子路由,调用console.log(this.$router.getRoutes());,查看控制台,确把test3,作为子路由添加到test1的路由下面了。但切换过去没有显示出来,切换其他静态路由也直接报错
这个怎么解决啊?
回复
1个回答
test
2024-07-09
组件部分多了一个箭头函数吧?另外如果是动态 addRoute
保证添加完成之后再执行 next()
回调。
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容