问题:vue3动态路由创建的时候,将所有的路由都添加到一级路由了(根路由)。怎么实现动态添加嵌套路由呢?
问题背景:在学习vue的时候,尝试做后台管理类项目练练手,其中包括动态路由,动态菜单,动态按钮。动态菜单已经实现,现在卡在动态路由上了。
使用版本:vue3
router/index.js
import {createRouter, createWebHistory} from "vue-router";
import {useMenusStore} from "@/store/index";
//静态路由
const routes = [
{
path: '/',
redirect: '/login'
},
{
path: '/login',
component: () => import('@/views/login')
},
]
const routerHistory = createWebHistory()
const router = createRouter({
history: routerHistory,
routes: routes
})
export default router
permission.js
import router from "@/router/index";
import {useMenusStore} from "@/store";
const Whitelist = ['/', '/login', 'error']
//全局路由守卫
router.beforeEach((to, from, next) => {
const store = useMenusStore()
if (Whitelist.indexOf(to.path) == -1) {
if (store.isLogin) {
if (!store.isRouter) {
//添加路由
router.addRoute(
{
path: '/home',
name: 'home',
meta: '真无语,咋就添不进来',
component: () =>
import('@/views/home/index.vue'),
children: [{
path: 'homepage',
meta: '为社么你你会是这样子',
component: () => import('@/views/home/content/index')
}, {
path: 'menu',
component: () => import('@/views/home/content/MenuManage/index')
}
]
},
)
console.log(router.getRoutes(), '查看现有路由')
// next()
next({...to, replace: true})
store.setIsRouter(true)
} else next()
} else {
next()
}
} else next()
})
然后会发现,所有添加的路由都添加成了根路由
然后再看home,发现children里面也有
也就是他不仅在根路由中全部创建还在子路由中也创建了。一头雾水啊。我想要的是一个嵌套路由,而不是将子级路由也创建到根路由上。
如果我将其改成这个样子,将父级路由定到静态路由中。他的子路由定到动态路由中
这个是router/index.js内容
...省略
const routes = [
{
path: '/',
redirect: '/login'
},
{
path: '/login',
component: () => import('@/views/login')
},
{
path: '/home',
name: 'home',
meta: '真无语,咋就添不进来',
component: () =>
import('@/views/home/index.vue'),
children:[]
}
]
...省略
//这个是permission.js内容
....省略
router.addRoute('home',
{
path: 'homepage',
meta: '为社么你你会是这样子',
component: () => import('@/views/home/content/index')
}
)
.....省略
会发现这个更糟,它直接将子路由添加到根路由中了。而父级路由的children是空的
第一种方法是对的,你直接在路由表里边这样子写打印出来的也是一样的