{"id":12564,"library":"vue-router","title":"Vue Router","description":"Vue Router is the official client-side routing library for Vue.js, providing robust and declarative navigation for single-page applications. The current stable version is 5.0.4, primarily designed for Vue 3 projects. It generally follows a regular release cadence, with minor bug fixes and experimental features being integrated frequently, and major versions released less often but incorporating significant architectural changes or merges. A key differentiator of Vue Router 5 is the integration of `unplugin-vue-router` into its core, enabling file-system based routing and simplifying route definition by convention. This merge aims to streamline development workflows, reducing boilerplate compared to earlier versions and offering a more integrated experience for large-scale applications. It also provides strong TypeScript support out of the box, ensuring type safety for route definitions and navigation guards.","status":"active","version":"5.0.4","language":"javascript","source_language":"en","source_url":"https://github.com/vuejs/router","tags":["javascript","typescript"],"install":[{"cmd":"npm install vue-router","lang":"bash","label":"npm"},{"cmd":"yarn add vue-router","lang":"bash","label":"yarn"},{"cmd":"pnpm add vue-router","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Used for data loading features, part of the Vue ecosystem integration.","package":"@pinia/colada","optional":true},{"reason":"Necessary for Single File Components (SFCs) compilation in a Vue 3 environment, especially with file-based routing.","package":"@vue/compiler-sfc","optional":false},{"reason":"Often used alongside Vue Router for state management in Vue 3 applications, particularly with data loaders.","package":"pinia","optional":true},{"reason":"The core framework that Vue Router is built for and deeply integrates with. Requires Vue 3.5.0 or higher.","package":"vue","optional":false}],"imports":[{"note":"Named export for creating a router instance. Vue Router 3 (for Vue 2) used a default export or `new VueRouter()`.","wrong":"import VueRouter from 'vue-router'","symbol":"createRouter","correct":"import { createRouter } from 'vue-router'"},{"note":"Used to configure HTML5 history mode (pushState API). Other history modes like `createWebHashHistory` or `createMemoryHistory` are also available.","wrong":"import { createHistory } from 'vue-router'","symbol":"createWebHistory","correct":"import { createWebHistory } from 'vue-router'"},{"note":"The component used to display the component matched by the current route. It's globally registered by default, but can be imported locally for explicit usage or type inference.","symbol":"RouterView","correct":"import { RouterView } from 'vue-router'"},{"note":"Composition API hook to access the router instance within a component. For Options API, use `this.$router`.","symbol":"useRouter","correct":"import { useRouter } from 'vue-router'"},{"note":"Type import for route locations, useful for type-checking navigation calls (`router.push`) and `RouterLink` `to` prop.","symbol":"RouteLocationRaw","correct":"import type { RouteLocationRaw } from 'vue-router'"}],"quickstart":{"code":"import { createApp } from 'vue'\nimport { createRouter, createWebHistory } from 'vue-router'\nimport App from './App.vue'\n\n// 1. Define route components.\nconst Home = { template: '<div>Home Page</div>' }\nconst About = { template: '<div>About Page</div>' }\nconst User = { \n  template: `\n    <div>\n      User {{ $route.params.id }}\n      <RouterLink :to=\"'/user/' + ($route.params.id as any) + '/profile'\">Profile</RouterLink>\n      <RouterLink :to=\"'/user/' + ($route.params.id as any) + '/posts'\">Posts</RouterLink>\n      <RouterView />\n    </div>\n  ` \n}\nconst UserProfile = { template: '<div>User Profile</div>' }\nconst UserPosts = { template: '<div>User Posts</div>' }\nconst NotFound = { template: '<div>404 Not Found</div>' }\n\n// 2. Define some routes\n// Each route should map to a component.\nconst routes = [\n  { path: '/', component: Home },\n  { path: '/about', component: About },\n  { \n    path: '/user/:id',\n    component: User,\n    children: [\n      { path: 'profile', component: UserProfile },\n      { path: 'posts', component: UserPosts },\n    ]\n  },\n  { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound },\n]\n\n// 3. Create the router instance and pass the `routes` option\nconst router = createRouter({\n  // 4. Provide the history implementation to use.\n  history: createWebHistory(process.env.BASE_URL ?? '/'),\n  routes, // short for `routes: routes`\n})\n\n// 5. Create and mount the root instance.\nconst app = createApp(App)\napp.use(router)\n\napp.mount('#app')\n\n/* In your App.vue template: */\n// <template>\n//   <h1>Hello Vue Router!</h1>\n//   <nav>\n//     <RouterLink to=\"/\">Go to Home</RouterLink>\n//     <RouterLink to=\"/about\">Go to About</RouterLink>\n//     <RouterLink to=\"/user/123\">Go to User 123</RouterLink>\n//     <RouterLink to=\"/non-existent\">Go to 404</RouterLink>\n//   </nav>\n//   <main>\n//     <RouterView />\n//   </main>\n// </template>\n\n// <script setup lang=\"ts\">\n// import { RouterLink, RouterView } from 'vue-router'\n// </script>\n","lang":"typescript","description":"This quickstart demonstrates the basic setup of Vue Router 5 with Vue 3, including route definitions, history mode, `RouterLink`, and `RouterView` components, and a catch-all 404 route."},"warnings":[{"fix":"Replace `throw miss()` with just `miss()` if you were explicitly throwing it. Adapt to `reroute()` instead of `NavigationResult` and remove usages of `selectNavigationResult`.","message":"In Vue Router v5.0.3, experimental features `miss()` now throws internally and returns `never`, instead of returning an error instance. Additionally, `reroute()` was added, and `NavigationResult` has been deprecated, with `selectNavigationResult` being removed.","severity":"breaking","affected_versions":">=5.0.3"},{"fix":"Update imports: `unplugin-vue-router/vite` to `vue-router/vite`, `unplugin-vue-router/data-loaders/*` to `vue-router/experimental`, `unplugin-vue-router` to `vue-router/unplugin`, and Volar plugins from `unplugin-vue-router/volar/*` to `vue-router/volar/*`. Remove `unplugin-vue-router` dependency.","message":"For developers migrating from `unplugin-vue-router` to Vue Router 5, import paths for the Vite plugin, data loaders, utility imports, and Volar plugins have changed.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"If relying on the `@vue/devtools-api` in an IIFE context, you may need to include it separately or adjust your build process. This primarily affects projects using the IIFE build directly for browser environments.","message":"The IIFE (Immediately Invoked Function Expression) build of Vue Router 5 no longer includes `@vue/devtools-api` because it has been upgraded to v8 and does not expose an IIFE build itself.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"Review routes and navigation logic that rely on the presence of query parameters. Explicitly mark them as required if their absence should lead to a different route match or behavior.","message":"In an experimental breaking change from v5.0.0-beta.1, query parameters are now optional by default. This might alter how routes with optional query parameters are matched or handled.","severity":"breaking","affected_versions":">=5.0.0-beta.1"},{"fix":"Update navigation guards to use `next({ path: '/path' })` or `return { path: '/path' }` for programmatic navigation, or `return '/path'` for simpler redirects. Avoid passing string arguments directly to `next()`.","message":"The `next()` callback with a string argument in navigation guards (e.g., `next('/path')`) has a deprecation warning in v5.0.3. It's recommended to use `next({ path: '/path' })` or `return '/path'` for better consistency and type safety.","severity":"deprecated","affected_versions":">=5.0.3"},{"fix":"Configure your web server (e.g., Nginx, Apache, or Node.js server) to redirect all unmatched paths to your `index.html` file. This allows Vue Router to take over client-side routing.","message":"When using `createWebHistory`, server configuration is required to handle direct access to deep links (e.g., refreshing a non-root page). Without it, the server might return a 404 error.","severity":"gotcha","affected_versions":">=4.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Catch the promise returned by `router.push()` or `router.replace()` to handle navigation failures gracefully: `router.push(...).catch(err => { if (isNavigationFailure(err, NavigationFailureType.duplicated)) console.log('Duplicate navigation'); })`. Alternatively, ensure your navigation logic only triggers when the target route is different.","cause":"Attempting to navigate to the same route (path and parameters) that the application is currently on, often triggered by `router.push()` or `RouterLink` clicks.","error":"Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location"},{"fix":"Ensure all intended paths are explicitly defined in your router's `routes` configuration. For unhandled paths, add a catch-all route (e.g., `{ path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFoundComponent }`) as the last entry in your `routes` array to render a 404 page.","cause":"The URL in the browser does not match any defined route in your `routes` array. This often happens with incorrect paths, typos, or missing catch-all routes.","error":"No match for current location: \"/some/invalid/path\""},{"fix":"After creating your `router` instance with `createRouter()`, make sure to call `app.use(router)` on your Vue application instance before mounting it: `const app = createApp(App); app.use(router); app.mount('#app');`.","cause":"The Vue Router instance was created but not registered with the Vue application instance using `app.use()`.","error":"Error: \"[Vue Router warn]: Router must be installed explicitly using `app.use(router)`\""},{"fix":"For Composition API (`<script setup>`), use `useRoute()` and `useRouter()` hooks directly: `const route = useRoute(); const router = useRouter();`. For Options API, ensure your `tsconfig.json` correctly includes `vue-router/client` types and that global properties are properly augmented if necessary, though `this.$route` and `this.$router` usually work out of the box with `app.use(router)`.","cause":"TypeScript error indicating that the `$route` or `$router` properties are not recognized within a component. This often occurs in `<script setup>` contexts or when types are not correctly inferred/augmented.","error":"Property '$route' does not exist on type '...' or 'Property '$router' does not exist on type '...'"}],"ecosystem":"npm"}