Vue3》》vite》》 vue-router 和文件路由
Vue-router
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'const routes = [{path: '/',name: 'Home',component: () => import('@/views/Home.vue')},{path: '/about',name: 'About',component: () => import('@/views/About.vue')},// 任意路由 - 必须放在最后{path: '/:pathMatch(.*)*',name: 'NotFound',component: () => import('@/views/NotFound.vue')}
]const router = createRouter({history: createWebHistory(),routes
})export default router
// Vue Router 3.x
{ path: '/:pathMatch(.*)', component: NotFound }// Vue Router 4.x
{ path: '/:pathMatch(.*)*', component: NotFound } // 注意多了 *Vue Router 4 推荐语法const routes = [// 捕获所有路径,包括子路径 要放在所有路由后面 {path: '/:pathMatch(.*)*',name: 'NotFound',component: NotFound},// 或者只捕获一级路径{path: '/:pathMatch(.*)',name: 'NotFound',component: NotFound},// 传统语法(仍然可用){path: '*',redirect: '/404'}
]
// 当访问以下路径时,都会匹配到 NotFound 组件
// /user/123 -> params.pathMatch = 'user/123'
// /products/abc/def -> params.pathMatch = 'products/abc/def'
// /any/thing/here -> params.pathMatch = 'any/thing/here'
const routes = [{path: '/admin',component: AdminLayout,children: [{path: 'dashboard',component: Dashboard},// 管理员区域的 404{path: ':pathMatch(.*)*',component: AdminNotFound}]},// 全局 404(必须放在最后){path: '/:pathMatch(.*)*',component: GlobalNotFound}
]
文件路由
src/layouts/default.vueadmin.vuepages/index.vueabout.vue[...all].vue # 全局 404admin/pages/dashboard.vueusers/index.vue[...all].vue # 管理员区域 404
src/pages/[...pathMatch].vue # 对应 /:pathMatch(.*)*[...catchAll].vue # 对应 /:catchAll(.*)* [...any].vue # 对应 /:any(.*)*