本来想用嵌套路由弄个管理员平台的,结果一直不显示。
需求:
访问 /admin 显示Welcme.vue组件
访问/admin/product显示Product.vue组件
import { createRouter, createWebHistory } from "vue-router";import Home from "@/views/Layout/index.vue";import Login from "@/views/Login/index.vue";const routes = [{path:"/admin",component:()=>import("@/admin/index.vue"),name:"admin",children:[{path:"/",name:"welcome",component:()=>import("@/admin/views/Welcome.vue")},{path:"/product",name:"product",component:()=>import("@/admin/components/Product.vue")},]},{path: "/",component: Home,],},{path: "/:pathMatch(.*)*",component: () => import("@/views/404/index.vue"),},];const router = createRouter({history: createWebHistory(),routes,});export default router;
结果发现只需要将子组件的路由的/去掉即可
这是因为子路由多写了/, 会默认从根目录开始匹配。
如下:
import { createRouter, createWebHistory } from "vue-router";import Home from "@/views/Layout/index.vue";import Login from "@/views/Login/index.vue";const routes = [{path:"/admin",component:()=>import("@/admin/index.vue"),name:"admin",children:[{path:"",name:"welcome",component:()=>import("@/admin/views/Welcome.vue")},{path:"product",name:"product",component:()=>import("@/admin/components/Product.vue")},]},{path: "/",component: Home,],},{path: "/:pathMatch(.*)*",component: () => import("@/views/404/index.vue"),},];const router = createRouter({history: createWebHistory(),routes,});export default router;
这样就能正常使用嵌套路由了