### Starting from Scratch with File-Based Routing Source: https://router.vuejs.org/zh/file-based-routing Example of setting up a new Vue project with file-based routing. Create a 'src/pages' folder and an 'index.vue' component for the homepage. ```typescript import { createApp } from 'vue' import { createRouter, createWebHistory } from 'vue-router' import { routes } from 'vue-router/auto-routes' import App from './App.vue' const router = createRouter({ history: createWebHistory(), routes, }) createApp(App) .use(router) .mount('#app') ``` -------------------------------- ### Initial Route Setup Source: https://router.vuejs.org/zh/guide/advanced/dynamic-routing Sets up a router with a catch-all dynamic route that renders the Article component. ```javascript const router = createRouter({ history: createWebHistory(), routes: [{ path: '/:articleName', component: Article }], }) ``` -------------------------------- ### Accessing Router and Route in setup Source: https://router.vuejs.org/zh/guide/advanced/composition-api.html Use `useRouter` and `useRoute` to access the router and route objects within the `setup` function when `this` is not available. ```javascript import { useRouter, useRoute } from 'vue-router' const router = useRouter() const route = useRoute() function pushWithQuery(query) { router.push({ name: 'search', query: { ...route.query, ...query, }, }) } ``` -------------------------------- ### Main Application Setup with File-Based Routing Source: https://router.vuejs.org/zh/file-based-routing Basic setup for a Vue application using the router created with file-based routing. ```typescript import { createApp } from 'vue' import { router } from './router' import App from './App.vue' createApp(App).use(router).mount('#app') ``` -------------------------------- ### Router Configuration Example Source: https://router.vuejs.org/zh/guide/essentials/passing-props This shows how to configure a route with a dynamic parameter '/users/:id' and associate it with the User component. ```javascript import User from './User.vue' // 传入 `createRouter` const routes = [{ path: '/users/:id', component: User }] ``` -------------------------------- ### Install Vue Router with bun Source: https://router.vuejs.org/zh/installation Use this command to install Vue Router in a project managed by bun. ```bash bun add vue-router ``` -------------------------------- ### Route Configuration Example Source: https://router.vuejs.org/zh/guide/essentials/active-links Defines a route with a dynamic username parameter and a nested route for role information. ```javascript const routes = [ { path: '/user/:username', component: User, children: [ { path: 'role/:roleId', component: Role, }, ], }, ] ``` -------------------------------- ### Create a new Vue project with Vue Router using bun Source: https://router.vuejs.org/zh/installation Use this command to create a new Vite-based project and include Vue Router during setup. ```bash bun create vue ``` -------------------------------- ### Install Vue Router with yarn Source: https://router.vuejs.org/zh/installation Use this command to install Vue Router in a project managed by yarn. ```bash yarn add vue-router ``` -------------------------------- ### Install Vue Router with pnpm Source: https://router.vuejs.org/zh/installation Use this command to install Vue Router in a project managed by pnpm. ```bash pnpm add vue-router ``` -------------------------------- ### Install Vue Router with npm Source: https://router.vuejs.org/zh/installation Use this command to install Vue Router in a project managed by npm. ```bash npm install vue-router ``` -------------------------------- ### Create a new Vue project with Vue Router using pnpm Source: https://router.vuejs.org/zh/installation Use this command to create a new Vite-based project and include Vue Router during setup. ```bash pnpm create vue ``` -------------------------------- ### Create a new Vue project with Vue Router using npm Source: https://router.vuejs.org/zh/installation Use this command to create a new Vite-based project and include Vue Router during setup. ```bash npm create vue@latest ``` -------------------------------- ### Multiple Path Parameters Example Source: https://router.vuejs.org/zh/guide/essentials/dynamic-matching Illustrates how multiple path parameters in a route definition map to corresponding fields in `$route.params`. This allows for more complex URL structures. ```markdown Matching Pattern| Matched Path| route.params ---|---|--- /users/:username| /users/eduardo| `{ username: 'eduardo' }` /users/:username/posts/:postId| /users/eduardo/posts/123| `{ username: 'eduardo', postId: '123' }` ``` -------------------------------- ### Create Router Instance with Routes Source: https://router.vuejs.org/zh/guide Defines routes by mapping URL paths to components and creates a router instance using createRouter. It uses createMemoryHistory for the example, but suggests createWebHistory or createWebHashHistory for actual applications. ```javascript import { createMemoryHistory, createRouter } from 'vue-router' import HomeView from './HomeView.vue' import AboutView from './AboutView.vue' const routes = [ { path: '/', component: HomeView }, { path: '/about', component: AboutView }, ] const router = createRouter({ history: createMemoryHistory(), routes, }) ``` -------------------------------- ### Create a new Vue project with Vue Router using yarn Source: https://router.vuejs.org/zh/installation Use this command to create a new Vite-based project and include Vue Router during setup. ```bash yarn create vue ``` -------------------------------- ### Navigation Guards with Composition API Source: https://router.vuejs.org/zh/guide/advanced/composition-api.html Implement navigation guards like `onBeforeRouteLeave` and `onBeforeRouteUpdate` as composable functions within the `setup` function. ```javascript import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router' import { ref } from 'vue' // 与 beforeRouteLeave 相同,无法访问 `this` onBeforeRouteLeave((to, from) => { const answer = window.confirm( 'Do you really want to leave? you have unsaved changes!' ) // 取消导航并停留在同一页面上 if (!answer) return false }) const userData = ref() // 与 beforeRouteUpdate 相同,无法访问 `this` onBeforeRouteUpdate(async (to, from) => { //仅当 id 更改时才获取用户,例如仅 query 或 hash 值已更改 if (to.params.id !== from.params.id) { userData.value = await fetchUser(to.params.id) } }) ``` -------------------------------- ### Navigate to Catch All Route Source: https://router.vuejs.org/zh/guide/essentials/dynamic-matching Programmatically navigate to a catch-all route, such as a 404 page, by constructing the `params` object with the appropriate `pathMatch` value. This example shows how to preserve existing query and hash values. ```javascript router.push({ name: 'NotFound', // Keep the current path, removing the first character to avoid the target URL starting with `//`. params: { pathMatch: this.$route.path.substring(1).split('/') }, // Preserve existing query and hash values, if any query: route.query, hash: route.hash, }) ``` -------------------------------- ### User Component Example Source: https://router.vuejs.org/zh/guide/essentials/passing-props This is a basic User component that displays a user ID. It initially depends on `$route.params.id`. ```vue ``` -------------------------------- ### RouterLink Example Source: https://router.vuejs.org/zh/guide/essentials/active-links Demonstrates two RouterLink components. The first links to a parent route, and the second links to a nested route. When the current path is '/user/erina/role/admin', both links will have the 'router-link-active' class, but only the second will have 'router-link-exact-active'. ```html User Role ``` -------------------------------- ### Integrating Layouts with Runtime Routes Source: https://router.vuejs.org/zh/file-based-routing/extending-routes Example of integrating layout management with runtime-extended routes, specifically using `vite-plugin-vue-layouts` which requires special handling for HMR. ```typescript import { createRouter } from 'vue-router' import { routes } from 'vue-router/auto-routes' import { setupLayouts } from 'virtual:generated-layouts' const router = createRouter({ // ... routes: setupLayouts(routes), }) ``` -------------------------------- ### Global Before Guard Example Source: https://router.vuejs.org/zh/guide/advanced/navigation-guards.html Register a global before guard using router.beforeEach to intercept and control navigation. You can return false to cancel navigation or a route location to redirect. ```javascript const router = createRouter({ ... }) router.beforeEach((to, from) => { // ... // 返回 false 以取消导航 return false }) ``` -------------------------------- ### Relative Redirect with Path Replacement Source: https://router.vuejs.org/zh/guide/essentials/redirect-and-alias Redirects to a relative path by manipulating the current path. This example replaces '/posts' with '/profile' in the URL. ```javascript const routes = [ { // 将总是把/users/123/posts重定向到/users/123/profile。 path: '/users/:id/posts', redirect: to => { // 该函数接收目标路由作为参数 return to.path.replace(/posts$/, 'profile') }, }, ] ``` -------------------------------- ### Route Configuration with Function Mode Props Source: https://router.vuejs.org/zh/guide/essentials/passing-props Configures a route to dynamically generate props based on the route object. This example extracts a query parameter 'q' and passes it as 'query' prop. ```javascript const routes = [ { path: '/search', component: SearchUser, props: route => ({ query: route.query.q }), }, ] ``` -------------------------------- ### Multiple Route Folders with Path Prefixes Source: https://router.vuejs.org/zh/file-based-routing/file-based-routing.html Configure path prefixes for each route folder, including parameters. Prefixes are used as-is and do not need to start or end with a slash. ```typescript import VueRouter from 'vue-router/vite' VueRouter({ routesFolder: [ 'src/pages', { src: 'src/admin/routes', // 注意总是有尾部斜杠,并且前面头部斜杠 path: 'admin/', // src/admin/routes/dashboard.vue -> /admin/dashboard }, { src: 'src/docs', // 你可以添加参数 path: 'docs/:lang/', // src/docs/introduction.vue -> /docs/:lang/introduction }, { src: 'src/promos', // 你可以省略尾部斜杠 path: 'promos-', // src/promos/black-friday.vue -> /promos-black-friday }, ], }) ``` -------------------------------- ### Async Global Before Guard Source: https://router.vuejs.org/zh/guide/advanced/navigation-guards.html Global before guards can be asynchronous. This example demonstrates awaiting a function that checks user access before allowing navigation. ```javascript router.beforeEach(async (to, from) => { // canUserAccess() 返回 `true` 或 `false` const canAccess = await canUserAccess(to) if (!canAccess) return '/login' }) ``` -------------------------------- ### Migrating Existing Project Routes with File-Based Routing Source: https://router.vuejs.org/zh/file-based-routing Example of migrating an existing Vue Router configuration to use file-based routing. Rename components and update the routes import. ```typescript import { createRouter, createWebHistory } from 'vue-router' import { routes, handleHotUpdate } from 'vue-router/auto-routes' export const router = createRouter({ history: createWebHistory(), routes: [ { path: '/', component: () => import('src/pages/Home.vue'), }, { path: '/users/:id', component: () => import('src/pages/User.vue'), } { path: '/about', component: () => import('src/pages/About.vue'), }, ] routes, }) // 这将在运行时更新路由而无需重新加载页面 if (import.meta.hot) { handleHotUpdate(router) } ``` -------------------------------- ### Dynamic Transitions Based on Navigation Source: https://router.vuejs.org/zh/guide/advanced/transitions Implement dynamic transitions by determining the transition name in an `afterEach` navigation hook. This example calculates the transition based on the depth of the target and current routes. ```html ``` ```javascript router.afterEach((to, from) => { const toDepth = to.path.split('/').length const fromDepth = from.path.split('/').length to.meta.transition = toDepth < fromDepth ? 'slide-right' : 'slide-left' }) ``` -------------------------------- ### Access Router and Route with Composition API Source: https://router.vuejs.org/zh/guide Shows how to access the router and current route instances using the useRouter() and useRoute() composition functions in the Composition API. It includes an example of using computed properties with route query parameters. ```vue ``` -------------------------------- ### Global Resolve Guard for Permissions Source: https://router.vuejs.org/zh/guide/advanced/navigation-guards.html Use router.beforeResolve to execute logic after all component guards and async route components have been resolved. This example checks for camera permissions before allowing navigation to a route that requires it. ```javascript router.beforeResolve(async to => { if (to.meta.requiresCamera) { try { await askForCameraPermission() } catch (error) { if (error instanceof NotAllowedError) { // ... 处理错误,然后取消导航 return false } else { // 意料之外的错误,取消导航并把错误传给全局处理器 throw error } } } }) ``` -------------------------------- ### Initial Route Configuration Source: https://router.vuejs.org/zh/guide/essentials/nested-routes Sets up the initial route configuration with a path for user details. ```javascript import User from './User.vue' // 这些都会传递给 `createRouter` const routes = [{ path: '/user/:id', component: User }] ``` -------------------------------- ### Getting All Routes Source: https://router.vuejs.org/zh/guide/advanced/dynamic-routing Retrieves an array of all currently registered route records using `router.getRoutes()`. ```javascript router.getRoutes() ``` -------------------------------- ### Using START_LOCATION in Navigation Guards Source: https://router.vuejs.org/zh/api Demonstrates how to use the START_LOCATION constant in navigation guards to identify the initial navigation. ```javascript import { START_LOCATION } from 'vue-router' router.beforeEach((to, from) => { if (from === START_LOCATION) { // initial navigation } }) ``` -------------------------------- ### Get matched components from currentRoute.matched Source: https://router.vuejs.org/zh/guide/migration Retrieve matched components from `router.currentRoute.value.matched` instead of using the removed `router.getMatchedComponents()` method. ```javascript router.currentRoute.value.matched.flatMap(record => Object.values(record.components) ) ``` -------------------------------- ### Creating a Router with Web History Source: https://router.vuejs.org/zh/api/interfaces/routeroptions Use `createWebHistory` for the history mode in most applications. This requires proper server configuration. ```javascript createRouter({ history: createWebHistory(), // 其它选项... }) ``` -------------------------------- ### Generated Type Declaration for Auto Routes Source: https://router.vuejs.org/zh/file-based-routing Example of the generated type declaration file for auto routes, defining the RouteNamedMap. ```typescript /* eslint-disable */ /* prettier-ignore */ // @ts-nocheck // Generated by vue-router. ‿️ 不要修改此文件 ‿️ // 建议提交此文件。 // 确保将此文件作为 "includes" 或 "files" 条目添加到你的 tsconfig.json 文件中。 declare module 'vue-router/auto-routes' { import type { RouteRecordInfo, ParamValue, ParamValueOneOrMore, ParamValueZeroOrMore, ParamValueZeroOrOne, } from 'vue-router' /** * Vue Router 基于文件的路由生成的路由名称映射 */ export interface RouteNamedMap { '/': RouteRecordInfo< '/', '/', Record, Record, | never > '/about': RouteRecordInfo< '/about', '/about', Record, Record, | never > '/users/[id]': RouteRecordInfo< '/users/[id]', '/users/:id', { id: ParamValue }, { id: ParamValue }, | never > } } ``` -------------------------------- ### Initialize Router: `new Router` vs `createRouter` Source: https://router.vuejs.org/zh/guide/migration Vue Router v4 uses factory functions instead of a class. Use `createRouter` instead of `new Router`. ```javascript import { createRouter } from 'vue-router' const router = createRouter({ // ... }) ``` -------------------------------- ### createMemoryHistory Source: https://router.vuejs.org/zh/api Creates a memory-based history object, primarily for server-side rendering. It starts from a special non-existent location that can be replaced by the user. ```APIDOC ## createMemoryHistory ### Description Creates a memory-based history object, primarily for server-side rendering. It starts from a special non-existent location that can be replaced by the user. ### Function Signature `createMemoryHistory(base?: string): RouterHistory` ### Parameters #### Path Parameters - **base** (string) - Optional - The base location for all URLs. Defaults to '/'. ### Returns - `RouterHistory` - A history object that can be passed to the router constructor. ``` -------------------------------- ### Globally Configuring Active Link Classes Source: https://router.vuejs.org/zh/guide/essentials/active-links Demonstrates how to set the default active and exact active link classes globally when creating the router instance. ```javascript const router = createRouter({ linkActiveClass: 'border-indigo-500', linkExactActiveClass: 'border-indigo-700', // ... }) ``` -------------------------------- ### Create Router with HTML5 History Source: https://router.vuejs.org/zh/guide/essentials/history-mode Use `createWebHistory()` for a clean, browser-like URL experience. This mode requires server-side configuration to handle direct access to routes. ```javascript import { createRouter, createWebHistory } from 'vue-router' const router = createRouter({ history: createWebHistory(), routes: [ //... ], }) ``` -------------------------------- ### RouterOptions Properties Source: https://router.vuejs.org/zh/api/interfaces/routeroptions Configuration options for initializing a Vue Router instance. ```APIDOC ## Interface: RouterOptions Used to initialize a Router instance. ### Properties #### end • `optional` **end**: `boolean` Whether the RegExp should end with a `$` to match the end. **Default value** `true` #### history • **history**: `RouterHistory` The history mode used by the router. Most applications should use `createWebHistory`, but this requires server configuration. You can also use `createWebHashHistory` for hash-based history, which does not require server configuration but is not SEO-friendly. **Example** ```javascript createRouter({ history: createWebHistory(), // other options... }) ``` #### linkActiveClass • `optional` **linkActiveClass**: `string` The default CSS class for RouterLink when the link is active. Defaults to `router-link-active`. #### linkExactActiveClass • `optional` **linkExactActiveClass**: `string` The default CSS class for RouterLink when the link is exactly active. Defaults to `router-link-exact-active`. #### parseQuery • `optional` **parseQuery**: (`search`: `string`) => `LocationQuery` Custom implementation to parse queries. See `stringifyQuery` for the corresponding implementation. **Example** ```javascript import qs from 'qs' createRouter({ // other options... parseQuery: qs.parse, stringifyQuery: qs.stringify, }) ``` #### routes • **routes**: `readonly` `RouteRecordRaw`[] The initial list of routes to add to the router. #### scrollBehavior • `optional` **scrollBehavior**: `RouterScrollBehavior` Controls scrolling when navigating between pages. Can return a Promise to defer scrolling. See `ScrollBehavior` for more details. **Example** ```javascript function scrollBehavior(to, from, savedPosition) { // `to` and `from` are route locations // `savedPosition` can be null } ``` #### sensitive • `optional` **sensitive**: `boolean` Makes the RegExp case-sensitive. **Default value** `false` #### strict • `optional` **strict**: `boolean` Disables trailing slashes. **Default value** `false` #### stringifyQuery • `optional` **stringifyQuery**: (`query`: `LocationQueryRaw`) => `string` Custom implementation to stringify a query object. This implementation should not prepend `?`. See `parseQuery` for the corresponding parsing implementation. ``` -------------------------------- ### Accessing Navigation Failure Properties Source: https://router.vuejs.org/zh/guide/advanced/navigation-failures Inspect the `to` and `from` properties of a navigation failure object to understand the intended destination and the starting point of the failed navigation. ```javascript // 正在尝试访问 admin 页面 router.push('/admin').then(failure => { if (isNavigationFailure(failure, NavigationFailureType.aborted)) { failure.to.path // '/admin' failure.from.path // '/' } }) ``` -------------------------------- ### Optional Parameters with '?' Source: https://router.vuejs.org/zh/guide/essentials/route-matching-syntax.html Marks a parameter as optional using the '?' modifier, allowing the route to match with or without the parameter present. Includes an example with a numeric constraint. ```javascript const routes = [ // match /users and /users/posva { path: '/users/:userId?' }, // match /users and /users/42 { path: '/users/:userId(\d+)?' }, ] ``` -------------------------------- ### Route Grouping for Organization Source: https://router.vuejs.org/zh/file-based-routing/file-based-routing.html Demonstrates how to use parentheses in folder names (e.g., `(admin)`) to group related routes logically without affecting the generated URL paths. ```text src/pages/ ├── (admin)/ │ ├── dashboard.vue │ └── settings.vue └── (user)/ ├── profile.vue └── order.vue ``` -------------------------------- ### Programmatic Navigation with Options API Source: https://router.vuejs.org/zh/guide Demonstrates how to navigate programmatically to a different route using the push() method on the $router instance within the Options API. ```javascript export default { methods: { goToAbout() { this.$router.push('/about') }, }, } ``` -------------------------------- ### Creating a Memory History Source: https://router.vuejs.org/zh/api Creates a memory-based history object, primarily for server-side rendering. This history starts from a special, non-existent location that can be replaced by the user. ```typescript const history = createMemoryHistory('/base/path') // pass history to the router constructor ``` -------------------------------- ### Create Web Hash History Source: https://router.vuejs.org/zh/api Demonstrates creating web hash history instances with different base paths. The base path is ignored for locations without a host. ```javascript // 基于 https://example.com/folder createWebHashHistory() // 给出一个 `https://example.com/folder#` 的 URL createWebHashHistory('/folder/') // 给出一个 `https://example.com/folder/#` 的 URL // 如果其基础位置提供了 `#`,则不会被 `createWebHashHistory` 添加 createWebHashHistory('/folder/#/app/') // 给出一个 `https://example.com/folder/#/app/` 的 URL // 你应该避免这样做,因为它改变了原始的 URL 且破坏了复制 URL 的工作 createWebHashHistory('/other-folder/') // 给出一个 `https://example.com/other-folder/#` 的 URL // 基于 file:///usr/etc/folder/index.html // 对于没有 `host` 的位置,该 base 会被忽略 createWebHashHistory('/iAmIgnored') // 给出一个 `file:///usr/etc/folder/index.html#` 的 URL ``` -------------------------------- ### Moving the `base` Configuration Source: https://router.vuejs.org/zh/guide/migration The `base` configuration is now passed as the first argument to `createWebHistory()` (and other history functions). ```javascript import { createRouter, createWebHistory } from 'vue-router' createRouter({ history: createWebHistory('/base-directory/'), routes: [], }) ``` -------------------------------- ### Basic Redirect to Root Path Source: https://router.vuejs.org/zh/guide/essentials/redirect-and-alias Redirects from '/home' to '/'. This is useful for setting a default landing page. ```javascript const routes = [{ path: '/home', redirect: '/' }] ``` -------------------------------- ### Global Build Version Imports Source: https://router.vuejs.org/zh/guide Demonstrates how to import Vue and Vue Router when using their global build versions, where they are exposed as global objects. ```javascript const { createApp } = Vue const { createRouter, createWebHistory } = VueRouter ``` -------------------------------- ### Custom File Extensions for Routes Source: https://router.vuejs.org/zh/file-based-routing/file-based-routing.html Configure custom file extensions for route definitions globally or per folder. For example, use markdown files as pages. ```typescript import VueRouter from 'vue-router/vite' VueRouter({ // 全局设置扩展名 extensions: ['.vue', '.md'], routesFolder: [ 'src/pages', { src: 'src/docs', // 覆盖全局扩展名以 **仅** 接受 markdown 文件 extensions: ['.md'], }, ], }) ``` -------------------------------- ### Wait for router to be ready before mounting app Source: https://router.vuejs.org/zh/guide/migration Ensure the router is ready before mounting the application, especially when using transitions or dealing with initial navigation guards. ```javascript app.use(router) // On the server, you need to manually navigate to the initial url router.isReady().then(() => app.mount('#app')) ``` -------------------------------- ### Handle history.pushState and history.replaceState Source: https://router.vuejs.org/zh/guide/migration Refactor manual `history.pushState` calls to use `router.push` and `history.replaceState` to preserve navigation information. ```javascript // replace history.pushState(myState, '', url) // with await router.push(url) history.replaceState({ ...history.state, ...myState }, '') ``` ```javascript // replace history.replaceState({}, '', url) // with history.replaceState(history.state, '', url) ``` -------------------------------- ### User Component with Props (Composition API) Source: https://router.vuejs.org/zh/guide/essentials/passing-props Refactored User component using Composition API's ` ``` -------------------------------- ### Creating a Router Instance Source: https://router.vuejs.org/zh/api Creates a Router instance that can be used by a Vue application. Requires RouterOptions as an argument. ```typescript const router = createRouter({ // ... history: createWebHashHistory(), routes: [] }) ``` -------------------------------- ### Basic HMR Setup for Vue Router Source: https://router.vuejs.org/zh/file-based-routing/hmr.html Configure your router to enable Hot Module Replacement (HMR) when using Vite. This prevents full page reloads when route definitions change. ```typescript import { createRouter, createWebHistory } from 'vue-router' import { routes, handleHotUpdate, } from 'vue-router/auto-routes' export const router = createRouter({ history: createWebHistory(), routes, }) // 这将在运行时更新路由而无需重新加载页面 if (import.meta.hot) { handleHotUpdate(router) } ``` -------------------------------- ### Netlify Redirects Configuration for HTML5 History Source: https://router.vuejs.org/zh/guide/essentials/history-mode Create a `_redirects` file to specify that all paths should be served by `index.html` with a 200 status code. ```netlify /* /index.html 200 ``` -------------------------------- ### Dynamic Route Parameters Source: https://router.vuejs.org/zh/file-based-routing/file-based-routing.html Shows how to create route parameters by enclosing the parameter name in brackets (e.g., `[id].vue` for `/:id`). Multiple parameters and parameters within static segments are also supported. ```text src/pages/users/[id].vue -> /users/:id src/pages/users_[id].vue -> /users_:id src/pages/product_[skuId]_[seoDescription].vue ``` -------------------------------- ### Caddy v2 Configuration for HTML5 History Source: https://router.vuejs.org/zh/guide/essentials/history-mode Use the `try_files` directive in Caddy v2 to serve `index.html` for requests that do not match existing files. ```caddy try_files {path} / ``` -------------------------------- ### Optional Route Parameters Source: https://router.vuejs.org/zh/file-based-routing/file-based-routing.html Demonstrates how to create optional route parameters by enclosing the parameter name in double brackets (e.g., `[[id]].vue` for `/:id?`). ```text src/pages/users/[[id]].vue -> /users/:id? ``` -------------------------------- ### Named Routes with Repeatable Parameters Source: https://router.vuejs.org/zh/guide/essentials/route-matching-syntax.html Demonstrates how to resolve named routes with repeatable parameters, showing empty and populated array cases for both '*' and '+'. ```javascript // Given { path: '/:chapters*', name: 'chapters' }, router.resolve({ name: 'chapters', params: { chapters: [] } }).href // yields / router.resolve({ name: 'chapters', params: { chapters: ['a', 'b'] } }).href // yields /a/b // Given { path: '/:chapters+', name: 'chapters' }, router.resolve({ name: 'chapters', params: { chapters: [] } }).href // throws an error because `chapters` is empty ``` -------------------------------- ### Vue Router ES module import map for CDN usage Source: https://router.vuejs.org/zh/installation Configure import maps to use Vue Router via CDN in an HTML file. This setup is recommended for direct browser usage without a build tool. ```html ``` -------------------------------- ### Basic Dynamic Routes Source: https://router.vuejs.org/zh/guide/essentials/route-matching-syntax.html Defines two routes with dynamic parameters, one for order IDs and another for product names. ```javascript const routes = [ // Match /o/3549 { path: '/o/:orderId' }, // Match /p/books { path: '/p/:productName' }, ] ``` -------------------------------- ### Route Configuration with Named Views and Props Source: https://router.vuejs.org/zh/guide/essentials/passing-props Demonstrates how to configure props for multiple named views within a single route. 'default' view receives params as props, while 'sidebar' does not. ```javascript const routes = [ { path: '/user/:id', components: { default: User, sidebar: Sidebar }, props: { default: true, sidebar: false }, }, ] ``` -------------------------------- ### Create Router with Hash History Source: https://router.vuejs.org/zh/guide/essentials/history-mode Use `createWebHashHistory()` to enable hash mode. This mode is simple as it doesn't require server-side configuration. ```javascript import { createRouter, createWebHashHistory } from 'vue-router' const router = createRouter({ history: createWebHashHistory(), routes: [ //... ], }) ``` -------------------------------- ### Defining Catch-all Routes with Regex Parameters Source: https://router.vuejs.org/zh/guide/migration The `*` wildcard route is removed. Use custom regex parameters like `/:pathMatch(.*)*` to define catch-all routes. This allows for dynamic routing and proper parameter handling. ```javascript const routes = [ // pathMatch is a parameter name, e.g. navigating to /not/found will get // { params: { pathMatch: ['not', 'found'] } } // This is necessary thanks to the last *, meaning repeated parameters, if you // intend to navigate to the unmatched path directly { path: '/:pathMatch(.*)*', name: 'not-found', component: NotFound }, // if you omit the last *, the `/` character in the parameter will be encoded when resolving or navigating { path: '/:pathMatch(.*)', name: 'bad-not-found', component: NotFound }, ] // If using named routes, a bad example: router.resolve({ name: 'bad-not-found', params: { pathMatch: 'not/found' }, }).href // '/not%2Ffound' // A good example: router.resolve({ name: 'not-found', params: { pathMatch: ['not', 'found'] }, }).href // '/not/found' ``` -------------------------------- ### Wildcard / 404 Route Source: https://router.vuejs.org/zh/file-based-routing/file-based-routing.html Demonstrates how to create a wildcard route for handling 404 Not Found errors by using three dots before the parameter name (e.g., `[...path].vue` for `/:path(.*)`). This can also be used within folders. ```text src/pages/[...path].vue -> /:path(.*) src/pages/articles/[...path].vue -> /articles/:path(.*) ``` -------------------------------- ### Navigate History with go() Source: https://router.vuejs.org/zh/api/interfaces/routerhistory Use the `go()` method to navigate through the browser's history. Pass a negative number to go back or a positive number to go forward. ```javascript myHistory.go(-1) // equivalent to window.history.back() myHistory.go(1) // equivalent to window.history.forward() ``` -------------------------------- ### Multiple Route Folders Source: https://router.vuejs.org/zh/file-based-routing/file-based-routing.html Provide multiple route folders by passing an array to `routesFolder`. ```javascript VueRouter({ routesFolder: ['src/pages', 'src/admin/routes'], }) ``` -------------------------------- ### Index Route Generation Source: https://router.vuejs.org/zh/file-based-routing/file-based-routing.html Demonstrates how `index.vue` files are used to generate empty paths for their parent directories, similar to an `index.html` file. ```text src/pages/index.vue: Generates / route src/pages/users/index.vue: Generates /users route ``` -------------------------------- ### Add router instance to app Source: https://router.vuejs.org/zh/guide/migration Optionally assign the app instance to `router.app` if needed, though it's no longer required for multi-app support. ```javascript app.use(router) router.app = app ``` -------------------------------- ### Handling Parameters with router.push Source: https://router.vuejs.org/zh/guide/essentials/navigation When using `params`, you can provide string or number arguments. For optional parameters, use an empty string or null. Avoid combining `params` with `path` in the same object; prefer using named routes. ```javascript const username = 'eduardo' // We can manually build the url, but we must handle encoding ourselves router.push(`/user/${username}`) // -> /user/eduardo // Similarly router.push({ path: `/user/${username}` }) // -> /user/eduardo // Benefit from automatic URL encoding with `name` and `params` if possible router.push({ name: 'user', params: { username } }) // -> /user/eduardo // `params` cannot be used with `path` router.push({ path: '/user', params: { username } }) // -> /user ``` -------------------------------- ### History Configuration: `mode` replaced by `history` Source: https://router.vuejs.org/zh/guide/migration The `mode` configuration is replaced by a more flexible `history` configuration. Use `createWebHistory()`, `createWebHashHistory()`, or `createMemoryHistory()` based on the desired mode. ```javascript import { createRouter, createWebHistory } from 'vue-router' // Also createWebHashHistory and createMemoryHistory createRouter({ history: createWebHistory(), routes: [], }) ``` -------------------------------- ### Fetch Data Before Navigation (Options API) Source: https://router.vuejs.org/zh/guide/advanced/data-fetching Fetches data before navigation is completed using the `beforeRouteEnter` and `beforeRouteUpdate` guards. This approach ensures data is available before the component is fully rendered or updated. Requires an `api.js` file with a `getPost` function. ```javascript export default { data() { return { post: null, error: null, } }, beforeRouteEnter(to, from, next) { try { const post = await getPost(to.params.id) // `setPost` 方法定义在下面的代码中 next(vm => vm.setPost(post)) } catch (err) { // `setError` 方法定义在下面的代码中 next(vm => vm.setError(err)) } }, // 路由改变前,组件就已经渲染完了 // 逻辑稍稍不同 async beforeRouteUpdate(to, from) { this.post = null getPost(to.params.id).then(this.setPost).catch(this.setError) }, methods: { setPost(post) { this.post = post }, setError(err) { this.error = err.toString() } } } ``` -------------------------------- ### Using Named Routes with Source: https://router.vuejs.org/zh/guide/essentials/named-routes Create navigation links using the 'name' property and pass 'params' for dynamic segments. This avoids hardcoding URLs and helps prevent typos. ```html User profile ``` -------------------------------- ### Custom Query Parsing and Stringifying with qs Source: https://router.vuejs.org/zh/api/interfaces/routeroptions Integrate the `qs` library for custom query parsing and stringifying by providing `parseQuery` and `stringifyQuery` implementations. ```javascript import qs from 'qs' createRouter({ // 其它选项... parseQuery: qs.parse, stringifyQuery: qs.stringify, }) ``` -------------------------------- ### Vercel Configuration for HTML5 History Source: https://router.vuejs.org/zh/guide/essentials/history-mode Create a `vercel.json` file to define rewrites, ensuring all paths are directed to `index.html`. ```json { "rewrites": [{ "source": "/:path*", "destination": "/index.html" }] } ``` -------------------------------- ### Create Router with Memory History Source: https://router.vuejs.org/zh/guide/essentials/history-mode Use `createMemoryHistory()` for Node.js environments or SSR. This mode does not interact with the URL and requires manual initial navigation. ```javascript import { createRouter, createMemoryHistory } from 'vue-router' const router = createRouter({ history: createMemoryHistory(), routes: [ //... ], }) ``` -------------------------------- ### Nested Named Routes Configuration Source: https://router.vuejs.org/zh/guide/essentials/nested-routes Demonstrates how to name child routes, ensuring a specific nested route ('user') is always displayed when navigating to '/user/:id'. ```javascript const routes = [ { path: '/user/:id', component: User, // 请注意,只有子路由具有名称 children: [{ path: '', name: 'user', component: UserHome }], }, ] ``` -------------------------------- ### Optional Repeatable Route Parameters Source: https://router.vuejs.org/zh/file-based-routing/file-based-routing.html Shows how to combine optional and repeatable parameters using double brackets and a plus sign (e.g., `[[slugs]]+.vue` for `/:slugs*`). ```text src/pages/articles/[[slugs]]+.vue -> /articles/:slugs* ``` -------------------------------- ### Asynchronous Navigation with await Source: https://router.vuejs.org/zh/guide/advanced/navigation-failures Use `await router.push()` to wait for navigation to complete before executing subsequent code. This ensures actions like closing a menu happen only after the new page is loaded. ```javascript router.push('/my-profile') this.isMenuOpen = false ``` ```javascript await router.push('/my-profile') this.isMenuOpen = false ``` -------------------------------- ### Configure routes in createRouter Source: https://router.vuejs.org/zh/guide/migration The `routes` property is now required when creating a router instance using `createRouter()`. ```javascript createRouter({ routes: [] }) ``` -------------------------------- ### Navigating Through History with router.go Source: https://router.vuejs.org/zh/guide/essentials/navigation The `router.go` method allows you to move forward or backward in the history stack by a specified number of steps, similar to `window.history.go(n)`. ```javascript // Move forward one record, same as router.forward() router.go(1) // Go back one record, same as router.back() router.go(-1) // Forward of 3 records router.go(3) // Silently fails if there aren't that many records router.go(-100) router.go(100) ``` -------------------------------- ### App.vue Template with Router Components Source: https://router.vuejs.org/zh/guide This template demonstrates the usage of RouterLink for navigation and RouterView for rendering route components. It also shows how to display the current route path using $route.fullPath. ```vue ``` -------------------------------- ### START_LOCATION Source: https://router.vuejs.org/zh/api The initial route location of the router. Can be used in navigation guards to differentiate initial navigation. ```APIDOC ## START_LOCATION ### Description The initial route location of the router. Can be used in navigation guards to differentiate initial navigation. ### Example ```javascript import { START_LOCATION } from 'vue-router' router.beforeEach((to, from) => { if (from === START_LOCATION) { // initial navigation } }) ``` ### Constant Declaration `const START_LOCATION: RouteLocationNormalizedLoaded` ``` -------------------------------- ### Navigating to Different Locations with router.push Source: https://router.vuejs.org/zh/guide/essentials/navigation Use `router.push` with a string path or an object to navigate. The object can specify `path`, `name`, `params`, `query`, or `hash` for detailed routing control. ```javascript router.push('/users/eduardo') router.push({ path: '/users/eduardo' }) router.push({ name: 'user', params: { username: 'eduardo' } }) router.push({ path: '/register', query: { plan: 'private' } }) router.push({ path: '/about', hash: '#team' }) ``` -------------------------------- ### Repeatable Route Parameters Source: https://router.vuejs.org/zh/file-based-routing/file-based-routing.html Explains how to create repeatable route parameters by adding a plus sign (`+`) after the closing bracket (e.g., `[slugs]+.vue` for `/:slugs+`). ```text src/pages/articles/[slugs]+.vue -> /articles/:slugs+ ``` -------------------------------- ### Nginx Server Configuration for HTML5 History Source: https://router.vuejs.org/zh/guide/essentials/history-mode Configure Nginx to use `try_files` to fall back to `index.html` for requests that do not match existing files or directories. ```nginx location / { try_files $uri $uri/ /index.html; } ``` -------------------------------- ### Basic Alias for a Root Path Source: https://router.vuejs.org/zh/guide/essentials/redirect-and-alias Assigns an alias '/home' to the root path '/'. The URL remains '/home' but matches the route for '/'. ```javascript const routes = [{ path: '/', component: Homepage, alias: '/home' }] ``` -------------------------------- ### Replacing `onReady` with `isReady` Source: https://router.vuejs.org/zh/guide/migration The `router.onReady()` function is replaced by `router.isReady()`, which returns a Promise and takes no arguments. Use `await router.isReady()` for asynchronous handling. ```javascript // Formerly // router.onReady(onSuccess, onError) // Replace with router.isReady().then(onSuccess).catch(onError) // Or using await: try { await router.isReady() // success } catch (err) { // error } ``` -------------------------------- ### useRouter Source: https://router.vuejs.org/zh/api Returns the router instance. This is equivalent to using `$router` in templates. ```APIDOC ## useRouter ### Description Returns the router instance. This is equivalent to using `$router` in templates. ### Returns `Router` ``` -------------------------------- ### 为路由元信息添加 TypeScript 类型 Source: https://router.vuejs.org/zh/guide/advanced/meta 通过扩展 `vue-router` 的 `RouteMeta` 接口,可以为 `meta` 字段添加类型定义,提高代码的可维护性和健壮性。确保此声明文件包含在 `tsconfig.json` 中。 ```typescript // 这段可以直接添加到你的任何 `.ts` 文件中,例如 `router.ts` // 也可以添加到一个 `.d.ts` 文件中。确保这个文件包含在 // 项目的 `tsconfig.json` 中的 "file" 字段内。 import 'vue-router' // 为了确保这个文件被当作一个模块,添加至少一个 `export` 声明 export {} declare module 'vue-router' { interface RouteMeta { // 是可选的 isAdmin?: boolean // 每个路由都必须声明 requiresAuth: boolean } } ``` -------------------------------- ### Naming Parent and Child Routes Source: https://router.vuejs.org/zh/guide/essentials/nested-routes Shows how to name both parent and child routes. Note that reloading the page on '/user/:id' will always display the nested child route. ```javascript const routes = [ { path: '/user/:id', name: 'user-parent', component: User, children: [{ path: '', name: 'user', component: UserHome }], }, ] ``` -------------------------------- ### Nested Routing with Sibling File for Different Path Source: https://router.vuejs.org/zh/file-based-routing/file-based-routing.html Explains how to create nested URL structures (e.g., `/users/create`) without nesting the UI component by using a dot in the filename (e.g., `users.create.vue`), which translates to a slash in the generated route. ```javascript const routes = [ { path: '/users', component: () => import('src/pages/users.vue'), children: [ { path: '', component: () => import('src/pages/users/index.vue') }, { path: ':id', component: () => import('src/pages/users/[id].vue') }, ], }, { path: '/users/create', component: () => import('src/pages/users.create.vue'), }, ] ``` -------------------------------- ### Route Configuration with Default Child Route Source: https://router.vuejs.org/zh/guide/essentials/nested-routes Configures a default (empty path) child route 'UserHome' to render when the parent '/user/:id' path is matched directly. ```javascript const routes = [ { path: '/user/:id', component: User, children: [ // 当 /user/:id 匹配成功 // UserHome 将被渲染到 User 的 内部 { path: '', component: UserHome }, // ...其他子路由 ], }, ] ```