?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;
}
?