vue 路由学习
params 不能传递对象类型如 [ ]和{ }
query传参
总结:
query传参既可以通过name 和path 找到路由规则里的组件,所以为了统一避免非必要麻烦
无论是使用query传参还是 params传参 映射路由建议统一使用 name
进阶 props的使用
备注:资料来自网络,尚硅谷
补充:思想我不想每次写完一个路由组件 就手动导入一次,我想自动完成注册,原理是根据组件之间嵌套关系写在特定的目录里,通过代码方式解析目录结构 的层级关系从而完成嵌套路由组件的注册
src/
└── pages/
└── user/
├── index.vue → /user
└── profile/
├── index.vue → /user/profile
└── detail/
└── index.vue → /user/profile/detail
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { promises as fs } from 'fs';const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);/*** 递归加载路由* @param dir 目录路径* @returns 路由记录数组*/
async function loadRoutes(dir: string): Promise<RouteRecordRaw[]> {const files = await fs.readdir(dir, { withFileTypes: true });const routes: RouteRecordRaw[] = [];for (const file of files) {const fullPath = join(dir, file.name);const relativePath = fullPath.replace(join(__dirname, '../pages'), '');const routePath = relativePath.replace(/(^\/|index\.vue$)/g, '').toLowerCase();if (file.isDirectory()) {// 如果是文件夹,则递归查找子路由const children = await loadRoutes(fullPath);if (children.length > 0 || file.name === 'profile') {// 尝试加载该目录下的 index.vue 作为默认组件let component;try {await fs.access(join(fullPath, 'index.vue'));component = () => import(`../pages${relativePath}/index.vue`);} catch (e) {console.warn(`[路由警告] ${relativePath} 缺少 index.vue`);}// 构建父级路由const parentRoute: RouteRecordRaw = {path: routePath || '/',name: file.name,component,children: children.length > 0 ? children : undefined,};routes.push(parentRoute);}} else if (file.isFile() && file.name.endsWith('.vue') && file.name !== 'index.vue') {// 如果是 .vue 文件(不是 index.vue),则直接作为子路由const componentName = file.name.replace(/\.vue$/, '');const component = () => import(`../pages${relativePath}`);routes.push({path: `${routePath}/${componentName}`,name: componentName,component,});}}return routes;
}// 创建路由实例
export async function setupRouter() {const routes = await loadRoutes(join(__dirname, '../pages'));const router = createRouter({history: createWebHistory(process.env.BASE_URL),routes, // 使用自动加载的路由配置});return router;
}