### Vue Router 3.0 Development Setup (Bash)
Source: https://github.com/vuejs/vue-router/blob/dev/README.md
This snippet outlines the commands to set up the development environment for Vue Router 3.0. It includes installing dependencies, building distribution files, serving examples, linting, running tests, and serving documentation.
```bash
# install deps
yarn
# build dist files
yarn build
# serve examples at localhost:8080
yarn dev
# lint & run all tests
yarn test
# serve docs at localhost:8080
yarn docs
```
--------------------------------
### Install and Setup Vue Router 3.x
Source: https://context7.com/vuejs/vue-router/llms.txt
Installs Vue Router via npm and registers it as a Vue plugin. It defines basic route components and creates a Vue Router instance with a history mode configuration. This setup enables routing capabilities for a Vue.js application.
```bash
npm install vue-router
```
```javascript
import Vue from 'vue'
import VueRouter from 'vue-router'
// Register the plugin
Vue.use(VueRouter)
// Define route components
const Home = { template: '
Home
' }
const About = { template: 'About
' }
const User = { template: 'User {{ $route.params.id }}
' }
// Create router instance with routes configuration
const router = new VueRouter({
mode: 'history', // Use HTML5 history mode (removes # from URLs)
base: '/', // Base URL of the app
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/user/:id', component: User }
]
})
// Create and mount the root instance
const app = new Vue({
router
}).$mount('#app')
// Access router and route in components:
// this.$router - the router instance
// this.$route - the current route object
```
--------------------------------
### Accessing Router and Route in Vue Components
Source: https://github.com/vuejs/vue-router/blob/dev/docs/guide/README.md
Shows how to access the Vue Router instance as `this.$router` and the current route information as `this.$route` within Vue components. It includes examples for accessing route parameters and navigating programmatically, like going back in history.
```javascript
// Home.vue
export default {
computed: {
username() {
// We will see what `params` is shortly
return this.$route.params.username
}
},
methods: {
goBack() {
window.history.length > 1 ? this.$router.go(-1) : this.$router.push('/')
}
}
}
```
--------------------------------
### Vue Router 3 JavaScript Configuration
Source: https://github.com/vuejs/vue-router/blob/dev/docs/guide/README.md
Configures Vue Router 3 by defining route components, setting up the routes array with paths and components, creating a VueRouter instance, and mounting the root Vue instance with the router. This setup enables client-side routing in a Vue.js application.
```javascript
// 0. If using a module system (e.g. via vue-cli), import Vue and VueRouter
// and then call `Vue.use(VueRouter)`.
// 1. Define route components.
// These can be imported from other files
const Foo = { template: 'foo
' }
const Bar = { template: 'bar
' }
// 2. Define some routes
// Each route should map to a component. The "component" can
// either be an actual component constructor created via
// `Vue.extend()`, or just a component options object.
// We'll talk about nested routes later.
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
// 3. Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const router = new VueRouter({
routes // short for `routes: routes`
})
// 4. Create and mount the root instance.
// Make sure to inject the router with the router option to make the
// whole app router-aware.
const app = new Vue({
router
}).$mount('#app')
// Now the app has started!
```
--------------------------------
### Basic HTML Structure for Vue Router 3
Source: https://github.com/vuejs/vue-router/blob/dev/docs/guide/README.md
Sets up the necessary HTML for a Vue.js application using Vue Router. It includes script tags for Vue and Vue Router, a root element for the Vue app, navigation links using ``, and a `` component where matched route components will be rendered.
```html
Hello App!
Go to Foo
Go to Bar
```
--------------------------------
### Build Vue Router from Source
Source: https://github.com/vuejs/vue-router/blob/dev/docs/installation.md
Clone the Vue Router repository from GitHub and build it locally to use the latest development version. This process involves cloning the repository, installing dependencies, and running the build script. It's intended for developers contributing to Vue Router or needing the absolute latest features.
```bash
git clone https://github.com/vuejs/vue-router.git node_modules/vue-router
cd node_modules/vue-router
npm install
npm run build
```
--------------------------------
### Install Vue Router using npm
Source: https://github.com/vuejs/vue-router/blob/dev/docs/installation.md
Install Vue Router as a project dependency using npm. This is the recommended approach for most modern Vue.js projects that use a module bundler like Webpack or Vite.
```bash
npm install vue-router
```
--------------------------------
### Manually Install Vue Router with Vue.use()
Source: https://github.com/vuejs/vue-router/blob/dev/docs/installation.md
When using Vue Router with a module system (like npm imports), you must explicitly install it using `Vue.use(VueRouter)`. This step is not required when using global script tags.
```js
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
```
--------------------------------
### Using START_LOCATION in Navigation Guards
Source: https://github.com/vuejs/vue-router/blob/dev/docs/api/README.md
Differentiate the initial navigation in navigation guards by comparing the 'from' route with `VueRouter.START_LOCATION`. This is useful for one-time setup logic.
```javascript
import VueRouter from 'vue-router';
const router = new VueRouter({
// ...
});
router.beforeEach((to, from) => {
if (from === VueRouter.START_LOCATION) {
console.log('Initial navigation');
}
});
```
--------------------------------
### Install Vue Router Plugin with Vue CLI
Source: https://github.com/vuejs/vue-router/blob/dev/docs/installation.md
Add Vue Router to a Vue CLI project using the `vue add router` command. This command automatically configures Vue Router, generates necessary files, and sets up sample routes. It will overwrite your `App.vue` file, so back it up first.
```sh
vue add router
```
--------------------------------
### Vue Router Fade Transition CSS
Source: https://github.com/vuejs/vue-router/blob/dev/examples/transitions/index.html
CSS for implementing a fade transition effect between Vue Router views. This requires the `.fade-enter-active`, `.fade-leave-active`, `.fade-enter`, and `.fade-leave-active` classes to be defined.
```css
.fade-enter-active, .fade-leave-active {
transition: opacity .75s ease;
}
.fade-enter, .fade-leave-active {
opacity: 0;
}
```
--------------------------------
### Include Vue Router via CDN
Source: https://github.com/vuejs/vue-router/blob/dev/docs/installation.md
This snippet shows how to include Vue Router in an HTML file using CDN links. Ensure Vue.js is included before Vue Router. This method is suitable for simple projects or when not using a module bundler.
```html
```
--------------------------------
### Vue Router Component Examples
Source: https://context7.com/vuejs/vue-router/llms.txt
Demonstrates various ways to use the `` component for declarative navigation in Vue Router. It covers basic links, named routes with parameters, query parameters, replacing history, exact matching, custom active classes, and the v-slot API for custom rendering.
```html
```
--------------------------------
### CSS Transitions for Fade Effect with Vue Router
Source: https://github.com/vuejs/vue-router/blob/dev/examples/navigation-guards/index.html
Demonstrates how to implement a fade transition effect for route changes in Vue Router using CSS. This involves defining styles for the enter and leave states of the transition. No JavaScript dependencies are required beyond Vue Router itself.
```css
.fade-enter-active, .fade-leave-active { transition: opacity .5s ease; }
.fade-enter, .fade-leave-active { opacity: 0; }
```
--------------------------------
### Vue Router Composables (Vue 2.7+)
Source: https://context7.com/vuejs/vue-router/llms.txt
Explains how to use Composition API composables like `useRouter`, `useRoute`, `useLink`, `onBeforeRouteUpdate`, and `onBeforeRouteLeave` in Vue 2.7+ applications. These composables provide reactive access to router and route properties and allow navigation guards within the `setup` function.
```javascript
import {
useRouter,
useRoute,
useLink,
onBeforeRouteUpdate,
onBeforeRouteLeave
} from 'vue-router/composables'
export default {
setup() {
const router = useRouter()
const route = useRoute()
// Reactive access to route properties
const userId = computed(() => route.params.id)
const searchQuery = computed(() => route.query.q)
// Programmatic navigation
function goToUser(id) {
router.push({ name: 'user', params: { id } })
}
// Navigation guards in setup
onBeforeRouteUpdate((to, from, next) => {
// Called when route params change
console.log('Route updating:', to.params)
next()
})
onBeforeRouteLeave((to, from, next) => {
// Prevent leaving with unsaved changes
if (hasUnsavedChanges.value) {
const confirmed = confirm('Discard changes?')
next(confirmed)
} else {
next()
}
})
// useLink for custom link components
const { href, route: linkRoute, navigate, isActive } = useLink({
to: { name: 'dashboard' }
})
return {
userId,
searchQuery,
goToUser,
href,
navigate,
isActive
}
}
}
```
--------------------------------
### Configure Catch-all / 404 Route in Vue Router
Source: https://github.com/vuejs/vue-router/blob/dev/docs/guide/essentials/dynamic-matching.md
This example shows how to configure a catch-all route using an asterisk (`*`) in Vue Router. This is commonly used for handling 404 Not Found scenarios. Ensure catch-all routes are defined at the end of your route configuration to maintain correct matching priority.
```javascript
{
// will match everything
path: '*'
}
```
```javascript
{
// will match anything starting with '/user-'
path: '/user-*'
}
```
--------------------------------
### Vue Router Link 'to' Prop Examples
Source: https://github.com/vuejs/vue-router/blob/dev/docs/api/README.md
Illustrates various ways to use the 'to' prop in to specify navigation targets. Supports string paths, location descriptor objects, named routes, and query parameters.
```html
Home
Home
```
```html
Home
```
```html
Home
```
```html
Home
```
```html
User
```
```html
Register
```
--------------------------------
### CSS for Fade and Slide Transitions
Source: https://context7.com/vuejs/vue-router/llms.txt
Provides CSS classes for implementing 'fade' and 'slide' route transitions. The '.fade-enter-active', '.fade-leave-active', '.slide-left-enter-active', and '.slide-right-leave-active' classes define the transition properties, while the '.fade-enter', '.fade-leave-to', '.slide-left-enter', etc., define the start and end states of the animation.
```css
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s ease;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
.slide-left-enter-active, .slide-left-leave-active,
.slide-right-enter-active, .slide-right-leave-active {
transition: transform 0.3s ease;
}
.slide-left-enter, .slide-right-leave-to {
transform: translateX(100%);
}
.slide-left-leave-to, .slide-right-enter {
transform: translateX(-100%);
}
```
--------------------------------
### Vue Router Slide Transition CSS
Source: https://github.com/vuejs/vue-router/blob/dev/examples/transitions/index.html
CSS for implementing slide transitions (left and right) between Vue Router views. This utilizes the `.child-view` class for positioning and specific classes like `.slide-left-enter` for animation.
```css
.child-view {
position: absolute;
transition: all .75s cubic-bezier(.55,0,.1,1);
}
.slide-left-enter, .slide-right-leave-active {
opacity: 0;
-webkit-transform: translate(30px, 0);
transform: translate(30px, 0);
}
.slide-left-leave-active, .slide-right-enter {
opacity: 0;
-webkit-transform: translate(-30px, 0);
transform: translate(-30px, 0);
}
```
--------------------------------
### Vue Router: Using Mixins with In-Component Guards (JavaScript)
Source: https://github.com/vuejs/vue-router/blob/dev/docs/guide/advanced/navigation-guards.md
Illustrates the correct way to use mixins that provide in-component navigation guards. It emphasizes installing the router plugin before applying the mixin.
```javascript
Vue.use(Router)
Vue.mixin({
beforeRouteUpdate(to, from, next) {
// ...
}
})
```
--------------------------------
### Link to Named Route with router-link
Source: https://github.com/vuejs/vue-router/blob/dev/docs/guide/essentials/named-routes.md
This example demonstrates how to create a link to a named route using the `router-link` component. The `to` prop accepts an object with the route's 'name' and any necessary 'params'.
```html
User
```
--------------------------------
### Vue Router Link 'replace' Prop Example
Source: https://github.com/vuejs/vue-router/blob/dev/docs/api/README.md
Shows how to use the 'replace' prop on . This causes navigation to use `router.replace()` instead of `router.push()`, preventing the new history record.
```html
```
--------------------------------
### Vue Router Link 'tag' Prop Example
Source: https://github.com/vuejs/vue-router/blob/dev/docs/api/README.md
Illustrates using the 'tag' prop to render as a different HTML element, like an ``. The component still handles click events for navigation.
```html
foo
foo
```
--------------------------------
### Initial Vue Router Configuration for a Single Route
Source: https://github.com/vuejs/vue-router/blob/dev/docs/guide/essentials/nested-routes.md
This JavaScript code demonstrates a basic Vue Router setup with a single route. It defines a component (`User`) and associates it with a path (`/user/:id`). This configuration is suitable for simple applications before introducing nested routes.
```javascript
const User = {
template: 'User {{ $route.params.id }}
'
}
const router = new VueRouter({
routes: [{ path: '/user/:id', component: User }]
})
```
--------------------------------
### Get Matched Components for a Location
Source: https://github.com/vuejs/vue-router/blob/dev/docs/api/README.md
Retrieve an array of component definitions or constructors that match a given location or the current route. This is particularly useful for server-side rendering to prefetch data.
```javascript
const matchedComponents = router.getMatchedComponents('/users/1');
console.log(matchedComponents);
```
--------------------------------
### Vue Router Link 'append' Prop Example
Source: https://github.com/vuejs/vue-router/blob/dev/docs/api/README.md
Demonstrates the 'append' prop for . When set to true, it appends the relative path to the current path, useful for nested navigation.
```html
```
--------------------------------
### Scroll to Anchor Element
Source: https://github.com/vuejs/vue-router/blob/dev/docs/guide/advanced/scroll-behavior.md
This example demonstrates how to implement "scroll to anchor" functionality. If the target route has a hash, it returns a selector to scroll to that element. An optional offset can be provided.
```javascript
scrollBehavior (to, from, savedPosition) {
if (to.hash) {
return {
selector: to.hash
// , offset: { x: 0, y: 10 } // offset only supported in 2.6.0+
}
}
}
```
--------------------------------
### Displaying $route.path in Vue.js Template
Source: https://github.com/vuejs/vue-router/blob/dev/examples/discrete-components/index.html
This snippet shows how to display the current route's path using the $route.path variable within a Vue.js template. It's commonly used to dynamically render content or highlight active links based on the URL. No external dependencies are required beyond Vue.js and Vue Router.
```html
$route.path value: {{ $route.path }}
```
--------------------------------
### Handle Initial Navigation Readiness with router.onReady
Source: https://github.com/vuejs/vue-router/blob/dev/docs/api/README.md
Queues a callback to be executed once the router has finished its initial navigation. This is particularly useful for server-side rendering to ensure consistent output. An optional error callback can handle initial route resolution errors.
```javascript
router.onReady(callback, [errorCallback])
```
--------------------------------
### Dynamic Route Registration with Vue Router
Source: https://context7.com/vuejs/vue-router/llms.txt
Demonstrates how to add and remove routes at runtime using the `addRoute` and `getRoutes` methods in Vue Router. This allows for flexible route management after the router has been initialized. It also shows how to add nested routes and conditionally add routes.
```javascript
const router = new VueRouter({
routes: [
{ path: '/', component: Home }
]
})
// Add a new route (3.5.0+)
const removeRoute = router.addRoute({
path: '/dynamic',
name: 'dynamic',
component: DynamicPage
})
// Add nested route under existing parent
router.addRoute('user', {
path: 'activity',
component: UserActivity
})
// Remove the added route
removeRoute()
// Get all registered routes
const routes = router.getRoutes()
console.log(routes.map(r => r.path))
// Check if route exists and add if not
if (!router.getRoutes().find(r => r.name === 'newFeature')) {
router.addRoute({
path: '/new-feature',
name: 'newFeature',
component: () => import('./views/NewFeature.vue')
})
}
```
--------------------------------
### Get All Active Route Records
Source: https://github.com/vuejs/vue-router/blob/dev/docs/api/README.md
Retrieve a list of all currently active route records in the router. Note that only documented properties are considered part of the public API.
```typescript
const routes = router.getRoutes();
console.log(routes);
```
--------------------------------
### router.onReady
Source: https://github.com/vuejs/vue-router/blob/dev/docs/api/README.md
Queues a callback to be executed once the router has completed its initial navigation, resolving all associated async hooks and components. It's particularly useful for server-side rendering to ensure consistent output. An optional error callback can be provided to handle errors during initial route resolution.
```APIDOC
## router.onReady
### Description
Queues a callback to be called when the router has completed the initial navigation, resolving all async enter hooks and async components associated with the initial route. Useful for server-side rendering.
### Method
`router.onReady(callback, [errorCallback])`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
router.onReady(function (currentRoute) {
// Initial navigation is complete
console.log('Initial navigation complete:', currentRoute);
}, function (error) {
// Handle initial navigation error
console.error('Initial navigation error:', error);
});
```
### Response
#### Success Response (N/A)
This method does not return a value directly but executes the provided callback.
#### Response Example
N/A
```
--------------------------------
### Vue Router 3.0 Release Process (Bash)
Source: https://github.com/vuejs/vue-router/blob/dev/README.md
This section details the steps for releasing a new version of Vue Router 3.0. It involves running tests, building distribution files with a specified version, generating a changelog, committing changes, tagging the release, and publishing to npm.
```bash
# yarn run release
# Ensure tests are passing `yarn run test`
# Build dist files `VERSION= yarn run build`
# Build changelog `yarn run changelog`
# Commit dist files `git add dist CHANGELOG.md && git commit -m "[build $VERSION]"`
# Publish a new version `npm version $VERSION --message "[release] $VERSION"
# Push tags `git push origin refs/tags/v$VERSION && git push`
# Publish to npm `npm publish`
```
--------------------------------
### Using and with
Source: https://github.com/vuejs/vue-router/blob/dev/docs/api/README.md
Demonstrates how to wrap with for animations and to preserve the state of components. It's important to place inside to ensure correct behavior.
```html
```
--------------------------------
### Route Guard Examples in Vue Router
Source: https://github.com/vuejs/vue-router/blob/dev/docs/api/README.md
Vue Router supports navigation guards directly within components: beforeRouteEnter, beforeRouteUpdate, and beforeRouteLeave. These guards allow control over navigation within component lifecycles.
```javascript
export default {
// ...
beforeRouteEnter(to, from, next) {
// Called when the route that the component belongs to is entered.
},
beforeRouteUpdate(to, from, next) {
// Called when the route info has changed, but component is reused.
},
beforeRouteLeave(to, from, next) {
// Called when the route that the component belongs to is leaving.
}
}
```
--------------------------------
### Vue Router Programmatic Navigation Methods
Source: https://context7.com/vuejs/vue-router/llms.txt
Illustrates how to perform navigation programmatically using the `$router` instance methods in Vue Router. It covers `push` with various arguments (string path, location object, named routes, query parameters), `replace`, and history manipulation methods like `go`, `forward`, and `back`.
```javascript
export default {
methods: {
navigateToUser() {
// Navigate using string path
this.$router.push('/user/123')
// Navigate using location object
this.$router.push({ path: '/user/123' })
// Navigate using named route with params
this.$router.push({ name: 'user', params: { id: '123' } })
// Navigate with query parameters
this.$router.push({
path: '/search',
query: { q: 'vue', page: 1 }
})
// Using promise (3.1.0+)
this.$router.push('/dashboard')
.then(() => {
console.log('Navigation complete')
})
.catch(err => {
// Handle navigation failures
if (err.name === 'NavigationDuplicated') {
// Navigated to same route
}
})
},
replaceRoute() {
// Replace current history entry (no back button)
this.$router.replace('/new-page')
this.$router.replace({ name: 'newPage' })
},
historyNavigation() {
// Go forward one step
this.$router.go(1)
// Equivalent to router.forward()
this.$router.forward()
// Go back one step
this.$router.go(-1)
// Equivalent to router.back()
this.$router.back()
// Go forward 3 steps
this.$router.go(3)
}
}
}
```
--------------------------------
### Router Construction Options
Source: https://github.com/vuejs/vue-router/blob/dev/docs/api/README.md
Global configuration options for the Vue Router instance.
```APIDOC
## Router Construction Options
### routes
- type: `Array`
Type declaration for `RouteConfig`:
```ts
interface RouteConfig = {
path: string,
component?: Component,
name?: string, // for named routes
components?: { [name: string]: Component }, // for named views
redirect?: string | Location | Function,
props?: boolean | Object | Function,
alias?: string | Array,
children?: Array, // for nested routes
beforeEnter?: (to: Route, from: Route, next: Function) => void,
meta?: any,
// 2.6.0+
caseSensitive?: boolean, // use case sensitive match? (default: false)
pathToRegexpOptions?: Object // path-to-regexp options for compiling regex
}
```
### mode
- type: `string`
- default: `"hash" (in browser) | "abstract" (in Node.js)`
- available values: `"hash" | "history" | "abstract"`
Configure the router mode.
- `hash`: uses the URL hash for routing. Works in all Vue-supported browsers, including those that do not support HTML5 History API.
- `history`: requires HTML5 History API and server config. See [HTML5 History Mode](../guide/essentials/history-mode.md).
- `abstract`: works in all JavaScript environments, e.g. server-side with Node.js. **The router will automatically be forced into this mode if no browser API is present.**
### base
- type: `string`
- default: `"/"`
The base URL of the app. For example, if the entire single page application is served under `/app/`, then `base` should use the value `"/app/"`.
### linkActiveClass
- type: `string`
- default: `"router-link-active"`
Globally configure `` default active class. Also see [router-link](#router-link).
```
--------------------------------
### Dynamically Determine Transition Name
Source: https://github.com/vuejs/vue-router/blob/dev/docs/guide/advanced/transitions.md
This example shows how to dynamically set the transition name based on the relationship between the current and target routes. It uses a watcher on the `$route` object to update a `transitionName` property, which is then bound to the `` component's name attribute.
```html
```
```javascript
// then, in the parent component,
// watch the `$route` to determine the transition to use
watch: {
'$route' (to, from) {
const toDepth = to.path.split('/').length
const fromDepth = from.path.split('/').length
this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left'
}
}
```
--------------------------------
### Coupling Component to $route (Vue.js)
Source: https://github.com/vuejs/vue-router/blob/dev/docs/guide/essentials/passing-props.md
This code snippet shows a component directly accessing `$route.params.id` to get the user ID. This creates a tight coupling with the router, limiting the component's flexibility and reusability as it can only be used on specific URLs.
```javascript
const User = {
template: 'User {{ $route.params.id }}
'
}
const router = new VueRouter({
routes: [{ path: '/user/:id', component: User }]
})
```
--------------------------------
### Router Instance Methods
Source: https://github.com/vuejs/vue-router/blob/dev/docs/api/README.md
Methods available on the router instance for navigation, route management, and hook registration.
```APIDOC
## Router Instance Methods
### router.beforeEach
### router.beforeResolve
### router.afterEach
Signatures:
```js
router.beforeEach((to, from, next) => {
/* must call `next` */
})
router.beforeResolve((to, from, next) => {
/* must call `next` */
})
router.afterEach((to, from) => {})
```
Add global navigation guards. See [Navigation Guards](../guide/advanced/navigation-guards.md) for more details. All three methods return a function that removes the registered guard/hook.
### router.push
### router.replace
### router.go
### router.back
### router.forward
Signatures:
```js
router.push(location, onComplete?, onAbort?)
router.push(location).then(onComplete).catch(onAbort)
router.replace(location, onComplete?, onAbort?)
router.replace(location).then(onComplete).catch(onAbort)
router.go(n)
router.back()
router.forward()
```
Programmatically navigate to a new URL. See [Programmatic Navigation](../guide/essentials/navigation.md) for more details. These functions can only be called after installing the Router plugin and passing it to the root Vue instance as shown in the [Getting Started](../guide/README.md).
### router.getMatchedComponents
Signature:
```js
const matchedComponents: Array = router.getMatchedComponents(location?)
```
Returns an Array of the components (definition/constructor, not instances) matched by the provided location or the current route. This is mostly used during server-side rendering to perform data prefetching.
### router.resolve
Signature:
```js
const resolved: {
location: Location;
route: Route;
href: string;
} = router.resolve(location, current?, append?)
```
Reverse URL resolving. Given location in form same as used in ``.
- `current` is the current Route by default (most of the time you don't need to change this)
- `append` allows you to append the path to the `current` route (as with [`router-link`](#router-link-props))
### router.addRoutes
_DEPRECATED_: use [`router.addRoute()`](#router-addroute) instead.
Signature:
```ts
router.addRoutes(routes: Array)
```
Dynamically add more routes to the router. The argument must be an Array using the same route config format with the `routes` constructor option.
### router.addRoute
> New in 3.5.0
Add a new route to the router. If the route has a `name` and there is already an existing one with the same one, it overwrites it.
Signature:
```ts
addRoute(route: RouteConfig): () => void
```
### router.addRoute
> New in 3.5.0
Add a new route record as the child of an existing route. If the route has a `name` and there is already an existing one with the same one, it overwrites it.
Signature:
```ts
addRoute(parentName: string, route: RouteConfig): () => void
```
### router.getRoutes
> New in 3.5.0
Get the list of all the active route records. **Note only documented properties are considered Public API**, avoid using any other property e.g. `regex` as it doesn't exist on Vue Router 4.
Signature:
```ts
getRoutes(): RouteRecord[]
```
```
--------------------------------
### Configure Redirects and Aliases in Vue Router
Source: https://context7.com/vuejs/vue-router/llms.txt
Set up redirects to map one path to another and aliases to provide alternative URLs for the same route. This allows for flexible URL structures and backward compatibility. Supports simple path mapping, named routes, dynamic redirects using functions, and multiple aliases for a single route.
```javascript
const router = new VueRouter({
routes: [
// Simple redirect
{ path: '/home', redirect: '/' },
// Redirect to named route
{ path: '/u/:id', redirect: { name: 'user' } },
// Dynamic redirect with function
{
path: '/search/:term',
redirect: to => {
// Return redirect path/location
return { path: '/results', query: { q: to.params.term } }
}
},
// Alias - URL stays the same, content from aliased route
{
path: '/user/:id',
component: User,
alias: '/profile/:id'
// Both /user/123 and /profile/123 show User component
// URL remains unchanged
},
// Multiple aliases
{
path: '/dashboard',
component: Dashboard,
alias: ['/home', '/main', '/start']
}
]
})
```
--------------------------------
### Configuration Options
Source: https://github.com/vuejs/vue-router/blob/dev/docs/api/README.md
Global configuration options for Vue Router, including active class, scroll behavior, and query string handling.
```APIDOC
## Configuration Options
### linkExactActiveClass
- type: `string`
- default: `"router-link-exact-active"`
Globally configure `` default active class for exact matches. Also see [router-link](#router-link).
### scrollBehavior
- type: `Function`
Signature:
```ts
type PositionDescriptor =
{ x: number, y: number } |
{ selector: string } |
void
type scrollBehaviorHandler = (
to: Route,
from: Route,
savedPosition?: { x: number, y: number }
) => PositionDescriptor | Promise
```
For more details see [Scroll Behavior](../guide/advanced/scroll-behavior.md).
### parseQuery / stringifyQuery
- type: `Function`
Provide custom query string parse / stringify functions. Overrides the default.
### fallback
- type: `boolean`
- default: `true`
Controls whether the router should fallback to `hash` mode when the browser does not support `history.pushState` but mode is set to `history`.
Setting this to `false` essentially makes every `router-link` navigation a full page refresh in IE9. This is useful when the app is server-rendered and needs to work in IE9, because a hash mode URL does not work with SSR.
```
--------------------------------
### Programmatic Navigation with push and replace
Source: https://github.com/vuejs/vue-router/blob/dev/docs/api/README.md
Navigate programmatically using `router.push` or `router.replace`. These methods accept a location object and can optionally take completion and abort callbacks, or return promises for handling navigation outcomes.
```javascript
router.push('/home');
router.replace({ path: '/about' });
router.push('/user/1', () => {
console.log('Navigation complete');
}, (err) => {
console.error('Navigation aborted:', err);
});
router.push('/settings').then(() => {
console.log('Settings page loaded');
}).catch(err => {
console.error('Error loading settings:', err);
});
```
--------------------------------
### Decoupling Component with Props: true (Vue.js)
Source: https://github.com/vuejs/vue-router/blob/dev/docs/guide/essentials/passing-props.md
This example demonstrates decoupling a component from the router by setting the `props` option to `true`. This automatically passes `route.params` as component props, allowing the component to receive the `id` directly via its `props` definition, enhancing reusability and testability.
```javascript
const User = {
props: ['id'],
template: 'User {{ id }}
'
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User, props: true },
// for routes with named views, you have to define the `props` option for each named view:
{
path: '/user/:id',
components: {
default: User,
sidebar: Sidebar
},
props: {
default: true,
// function mode, more about it below
sidebar: route => ({ search: route.query.q })
}
}
]
})
```
--------------------------------
### Dynamic Route Matching with Vue Router
Source: https://context7.com/vuejs/vue-router/llms.txt
Defines routes with dynamic segments using colon syntax. Parameters are accessed via `$route.params`. Supports single/multiple segments, optional parameters, and catch-all routes.
```javascript
const router = new VueRouter({
routes: [
// Single dynamic segment
{ path: '/user/:id', component: User },
// Multiple dynamic segments
{ path: '/user/:username/post/:postId', component: Post },
// Optional parameter (using regex)
{ path: '/optional/:id?', component: OptionalParam },
// Catch-all route (404)
{ path: '*', component: NotFound },
// Catch-all with prefix
{ path: '/files-*', component: FileViewer }
]
})
// Component accessing route params
const User = {
template: 'User ID: {{ $route.params.id }}
',
// Watch for param changes (same component reused)
watch: {
'$route'(to, from) {
// Fetch new user data when id changes
this.fetchUser(to.params.id)
}
},
// Or use beforeRouteUpdate guard
beforeRouteUpdate(to, from, next) {
this.fetchUser(to.params.id)
next()
},
methods: {
fetchUser(id) {
// Fetch user data...
}
}
}
// Catch-all route provides pathMatch param
// URL: /files-documents/reports/2023
// $route.params.pathMatch === 'documents/reports/2023'
```
--------------------------------
### Programmatic Navigation with router.push - Vue Router
Source: https://github.com/vuejs/vue-router/blob/dev/docs/guide/essentials/navigation.md
Demonstrates navigating programmatically using `router.push` with string paths, location descriptor objects, named routes, and query parameters. This method pushes a new entry into the history stack.
```javascript
router.push('home')
// object
router.push({ path: 'home' })
// named route
router.push({ name: 'user', params: { userId: '123' } })
// with query, resulting in /register?plan=private
router.push({ path: 'register', query: { plan: 'private' } })
const userId = '123'
router.push({ name: 'user', params: { userId } }) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// This will NOT work
router.push({ path: '/user', params: { userId } }) // -> /user
```
--------------------------------
### Navigating with router.go, back, and forward
Source: https://github.com/vuejs/vue-router/blob/dev/docs/api/README.md
Control navigation history using `router.go(n)` to move forward or backward by n steps, `router.back()` to go to the previous entry, and `router.forward()` to go to the next entry in the history.
```javascript
router.go(1); // Forward one step
router.go(-1); // Back one step
router.back();
router.forward();
```
--------------------------------
### Dynamic Props with Function Mode (Vue.js)
Source: https://github.com/vuejs/vue-router/blob/dev/docs/guide/essentials/passing-props.md
This example shows how to use the function mode for the `props` option. It enables dynamic prop generation based on the route object, allowing for type casting, combining static and route-based values, or transforming route parameters. The URL `/search?q=vue` will pass `{query: 'vue'}` as props to the `SearchUser` component.
```javascript
const router = new VueRouter({
routes: [
{
path: '/search',
component: SearchUser,
props: route => ({ query: route.query.q })
}
]
})
```
--------------------------------
### Navigating History with router.go - Vue Router
Source: https://github.com/vuejs/vue-router/blob/dev/docs/guide/essentials/navigation.md
Shows how to use `router.go(n)` to navigate forwards or backwards in the browser's history stack by a specified number of steps. This method is analogous to `window.history.go(n)`.
```javascript
// go forward by one record, the same as history.forward()
router.go(1)
// go back by one record, the same as history.back()
router.go(-1)
// go forward by 3 records
router.go(3)
// fails silently if there aren't that many records.
router.go(-100)
router.go(100)
```
--------------------------------
### Dynamic Import for Code Splitting - JavaScript
Source: https://github.com/vuejs/vue-router/blob/dev/docs/guide/advanced/lazy-loading.md
Demonstrates the use of webpack's dynamic import syntax to indicate a code-splitting point. This returns a Promise that resolves to the module, enabling lazy loading.
```javascript
import('./Foo.vue') // returns a Promise
```
--------------------------------
### Combine Async Component and Dynamic Import - JavaScript
Source: https://github.com/vuejs/vue-router/blob/dev/docs/guide/advanced/lazy-loading.md
Combines Vue's async component factory with webpack's dynamic import syntax. This allows webpack to automatically code-split the component into a separate chunk.
```javascript
const Foo = () => import('./Foo.vue')
```
--------------------------------
### Per-Route Transitions with Vue Router Meta
Source: https://context7.com/vuejs/vue-router/llms.txt
Allows defining specific transitions for individual routes via meta fields. The transition name is dynamically bound to `transitionName`, which reads from `$route.meta.transition` or defaults to 'fade'. This enables route-specific animations.
```html
```
--------------------------------
### Router Instance Properties
Source: https://github.com/vuejs/vue-router/blob/dev/docs/api/README.md
Properties available on the router instance, providing access to the current route, application instance, and mode.
```APIDOC
## Router Instance Properties
### router.app
- type: `Vue instance`
The root Vue instance the `router` was injected into.
### router.mode
- type: `string`
The [mode](./#mode) the router is using.
### router.currentRoute
- type: `Route`
The current route represented as a [Route Object](#the-route-object).
### router.START_LOCATION (3.5.0+)
- type: `Route`
Initial route location represented as a [Route Object](#the-route-object) where the router starts at. Can be used in navigation guards to differentiate the initial navigation.
```js
import VueRouter from 'vue-router'
const router = new VueRouter({
// ...
})
router.beforeEach((to, from) => {
if (from === VueRouter.START_LOCATION) {
// initial navigation
}
})
```
```
--------------------------------
### Detecting Navigation Failures
Source: https://github.com/vuejs/vue-router/blob/dev/docs/guide/advanced/navigation-failures.md
Demonstrates how to use the `isNavigationFailure` function to detect specific types of navigation failures when using `router.push`.
```APIDOC
## POST /router.push (with failure handling)
### Description
Handles potential navigation failures when using `router.push`. This example shows how to catch a rejected promise from `router.push` and check if the failure is of type `NavigationFailureType.redirected`.
### Method
`POST` (simulated for `router.push`)
### Endpoint
`/router.push`
### Parameters
#### Query Parameters
- **failure** (Error) - Required - The error object representing the navigation failure.
- **NavigationFailureType** (Enum) - Required - The type of navigation failure to check against.
#### Request Body
None
### Request Example
```javascript
import VueRouter from 'vue-router'
const { isNavigationFailure, NavigationFailureType } = VueRouter
// trying to access the admin page
router.push('/admin').catch(failure => {
if (isNavigationFailure(failure, NavigationFailureType.redirected)) {
// show a small notification to the user
showToast('Login in order to access the admin panel')
}
})
```
### Response
#### Success Response (200)
Navigation completes successfully.
#### Error Response (Promise Rejection)
- **failure** (Error) - Contains properties `to` and `from` detailing the navigation attempt.
#### Response Example
```json
{
"to": {
"path": "/admin"
},
"from": {
"path": "/"
}
}
```
### NavigationFailureType Enum
- **redirected**: `next(newLocation)` was called inside a navigation guard.
- **aborted**: `next(false)` was called inside a navigation guard.
- **cancelled**: A new navigation occurred before the current one finished.
- **duplicated**: Navigation prevented because the target location is the current location.
```
--------------------------------
### Vue.js: Fetching Data After Navigation in Component
Source: https://github.com/vuejs/vue-router/blob/dev/docs/guide/advanced/data-fetching.md
This snippet demonstrates fetching data within a Vue component's lifecycle hooks after the route has been navigated. It includes template for displaying loading, error, and content states, and JavaScript for data fetching logic using `created` and `watch`.
```html
Loading...
{{ error }}
{{ post.title }}
{{ post.body }}
```
```javascript
export default {
data () {
return {
loading: false,
post: null,
error: null
}
},
created () {
// fetch the data when the view is created and the data is
// already being observed
this.fetchData()
},
watch: {
// call again the method if the route changes
'$route': 'fetchData'
},
methods: {
fetchData () {
this.error = this.post = null
this.loading = true
const fetchedId = this.$route.params.id
// replace `getPost` with your data fetching util / API wrapper
getPost(fetchedId, (err, post) => {
// make sure this request is the last one we did, discard otherwise
if (this.$route.params.id !== fetchedId) return
this.loading = false
if (err) {
this.error = err.toString()
} else {
this.post = post
}
})
}
}
}
```
--------------------------------
### Basic Route Transitions with Vue Router
Source: https://context7.com/vuejs/vue-router/llms.txt
Applies a 'fade' transition to all route changes using the `` component wrapping ``. The `mode='out-in'` ensures the outgoing view is removed before the incoming view is added, preventing overlap.
```html
```
--------------------------------
### Route Transitions with Keep-Alive Caching
Source: https://context7.com/vuejs/vue-router/llms.txt
Combines route transitions with Vue's `` component for caching. Routes can be selectively cached based on meta fields. The `:key="$route.fullPath"` on `` ensures that even if the component is the same, a new instance is rendered when the full path changes, which is important for transitions.
```html
```