### Install Vue Router using npm Source: https://v3.router.vuejs.org/installation Install the vue-router package using npm for use in module systems. ```bash npm install vue-router ``` -------------------------------- ### Manually Install Vue Router with Vue.use() Source: https://v3.router.vuejs.org/installation When using a module system, explicitly install Vue Router using Vue.use() after importing Vue and VueRouter. ```javascript import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) ``` -------------------------------- ### Coupling to $route Source: https://v3.router.vuejs.org/guide/essentials/passing-props This example shows how to directly use `$route.params.id` within a component, creating a tight coupling with the router. ```javascript const User = { template: '
User {{ $route.params.id }}
' } const router = new VueRouter({ routes: [{ path: '/user/:id', component: User }] }) ``` -------------------------------- ### JavaScript Setup for Vue Router 3 Source: https://v3.router.vuejs.org/guide Define route components, configure routes with paths and components, create a VueRouter instance, and mount the root Vue instance with the router. ```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! ``` -------------------------------- ### Route Object Properties Example Source: https://v3.router.vuejs.org/api Illustrates accessing route object properties like path, params, query, meta, hash, fullPath, and matched within a component context. ```javascript this.$route.path this.$route.params this.$route.query this.$route.meta this.$route.hash this.$route.fullPath this.$route.matched ``` -------------------------------- ### Decoupling with props: true Source: https://v3.router.vuejs.org/guide/essentials/passing-props This example demonstrates decoupling a component by setting `props: true` in the route configuration. This passes `route.params` as component props. ```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 }) } } ] }) ``` -------------------------------- ### router.START_LOCATION Source: https://v3.router.vuejs.org/api The initial route location object where the router starts. Useful for differentiating initial navigation. ```APIDOC ## router.START_LOCATION (3.5.0+) ### Description The initial route location object where the router starts. Useful for differentiating initial navigation. ### Type `Route` ### Example ```javascript import VueRouter from 'vue-router' const router = new VueRouter({ // ... }) router.beforeEach((to, from) => { if (from === VueRouter.START_LOCATION) { // initial navigation } }) ``` ``` -------------------------------- ### Mixin Navigation Guard Placement Source: https://v3.router.vuejs.org/guide/advanced/navigation-guards Example showing the correct placement of `Vue.use(Router)` before `Vue.mixin` to ensure in-component navigation guards from mixins are properly registered. ```javascript Vue.use(Router) Vue.mixin({ beforeRouteUpdate(to, from, next) { // ... } }) ``` -------------------------------- ### Programmatic Navigation Source: https://v3.router.vuejs.org/api Navigate programmatically using `push`, `replace`, `go`, `back`, or `forward`. These methods require the router plugin to be installed. ```javascript router.push(location, onComplete?, onAbort?) router.push(location).then(onComplete).catch(onAbort) ``` ```javascript router.replace(location, onComplete?, onAbort?) router.replace(location).then(onComplete).catch(onAbort) ``` ```javascript router.go(n) ``` ```javascript router.back() ``` ```javascript router.forward() ``` -------------------------------- ### router.push / router.replace / router.go / router.back / router.forward Source: https://v3.router.vuejs.org/api Methods for programmatic navigation. `push` and `replace` navigate to a new URL, while `go`, `back`, and `forward` control history traversal. These methods can be called after the Router plugin is installed. ```APIDOC ## router.push / router.replace / router.go / router.back / router.forward ### Description Methods for programmatic navigation. `push` and `replace` navigate to a new URL, while `go`, `back`, and `forward` control history traversal. These methods can be called after the Router plugin is installed. ### Signatures ```javascript 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() ``` ``` -------------------------------- ### Include Vue Router via CDN Source: https://v3.router.vuejs.org/installation Include the vue-router.js script after Vue.js in your HTML for automatic installation. ```html ``` -------------------------------- ### Router-link 'to' prop examples Source: https://v3.router.vuejs.org/api The 'to' prop specifies the target route. It can be a literal string, a javascript expression, or a location descriptor object. ```html Home Home Home Home Home User Register ``` -------------------------------- ### Global Before Guard - Correct next() Usage Source: https://v3.router.vuejs.org/guide/advanced/navigation-guards This example demonstrates the correct usage of the `next` function in a global before guard, ensuring `next` is called exactly once to resolve the hook, preventing navigation issues. ```javascript // GOOD router.beforeEach((to, from, next) => { if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' }) else next() }) ``` -------------------------------- ### Route Record Configuration Source: https://v3.router.vuejs.org/api Example of defining nested route records within a Vue Router configuration, including path, component, and children properties. ```javascript const router = new VueRouter({ routes: [ // the following object is a route record { path: '/foo', component: Foo, children: [ // this is also a route record { path: 'bar', component: Bar } ] } ] }) ``` -------------------------------- ### Dynamic Props with Function Mode Source: https://v3.router.vuejs.org/guide/essentials/passing-props Function mode allows dynamic prop generation based on the route. This example passes query parameters as a prop, casting them as needed. ```javascript const router = new VueRouter({ routes: [ { path: '/search', component: SearchUser, props: route => ({ query: route.query.q }) } ] }) ``` -------------------------------- ### HTML Setup for Vue Router 3 Source: https://v3.router.vuejs.org/guide Include Vue.js and Vue Router via CDN in your HTML. This sets up the basic structure for a Vue application with a router-enabled view. ```html

Hello App!

Go to Foo Go to Bar

``` -------------------------------- ### Install Vue Router Plugin with Vue CLI Source: https://v3.router.vuejs.org/installation Add Vue Router as a plugin to a Vue CLI project. This command also generates sample routes and may overwrite App.vue. ```bash vue add router ``` -------------------------------- ### Get Matched Components Source: https://v3.router.vuejs.org/api Retrieve an array of matched components for a given location or the current route using `getMatchedComponents`. Useful for server-side rendering data prefetching. ```javascript const matchedComponents: Array = router.getMatchedComponents(location?) ``` -------------------------------- ### Global Before Guard - Incorrect next() Usage Source: https://v3.router.vuejs.org/guide/advanced/navigation-guards This example shows incorrect usage of the `next` function in a global before guard, where `next` can be called twice with overlapping logic, leading to unresolved hooks or errors. ```javascript // BAD router.beforeEach((to, from, next) => { if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' }) // if the user is not authenticated, `next` is called twice next() }) ``` -------------------------------- ### Get All Active Routes Source: https://v3.router.vuejs.org/api Retrieve an array of all active route records using `getRoutes`. Note that only documented properties are considered part of the public API. ```javascript getRoutes(): RouteRecord[] ``` -------------------------------- ### Initial Navigation Check Source: https://v3.router.vuejs.org/api Use `VueRouter.START_LOCATION` in navigation guards to identify the initial navigation event. ```javascript import VueRouter from 'vue-router' const router = new VueRouter({ // ... }) router.beforeEach((to, from) => { if (from === VueRouter.START_LOCATION) { // initial navigation } }) ``` -------------------------------- ### Using Transition and Keep-Alive with Router View Source: https://v3.router.vuejs.org/api Demonstrates how to use `` and `` components with ``. Ensure `` is nested inside `` for correct behavior. ```html ``` -------------------------------- ### router.onReady Source: https://v3.router.vuejs.org/api Queues a callback to be executed once the router has completed its initial navigation. This is 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 components. Useful for server-side rendering to ensure consistent output. An optional `errorCallback` can be provided to handle errors during initial route resolution (supported in v2.4+). ### Signature ``` router.onReady(callback, [errorCallback]) ``` ``` -------------------------------- ### Basic Route Configuration Source: https://v3.router.vuejs.org/guide/essentials/nested-routes A simple route configuration for a top-level route that renders a User component. ```javascript const User = { template: '
User {{ $route.params.id }}
' } const router = new VueRouter({ routes: [{ path: '/user/:id', component: User }] }) ``` -------------------------------- ### Router Construction Options Source: https://v3.router.vuejs.org/api Options available when constructing the router instance. ```APIDOC ## Router Construction Options ### # routes * type: `Array` Type declaration for `RouteConfig`: ``` 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. * `history`: requires HTML5 History API and server config. * `abstract`: works in all JavaScript environments. ### # base * type: `string` * default: `"/"` The base URL of the app. ### # linkActiveClass * type: `string` * default: `"router-link-active"` Globally configure `` default active class. ### # linkExactActiveClass * type: `string` * default: `"router-link-exact-active"` Globally configure `` default active class for exact matches. ``` -------------------------------- ### Basic App Structure Source: https://v3.router.vuejs.org/guide/essentials/nested-routes The root HTML element where the Vue app is mounted and the main router-view outlet is defined. ```html
``` -------------------------------- ### Route Guard Navigation Arguments Source: https://v3.router.vuejs.org/api Demonstrates the 'to' and 'from' route objects passed as arguments to the beforeEach navigation guard. ```javascript router.beforeEach((to, from, next) => { // `to` and `from` are both route objects }) ``` -------------------------------- ### Build Vue Router from Development Build Source: https://v3.router.vuejs.org/installation Clone the Vue Router repository from GitHub and build the latest development version. This is necessary for using the dev build. ```bash git clone https://github.com/vuejs/vue-router.git node_modules/vue-router cd node_modules/vue-router npm install npm run build ``` -------------------------------- ### Nginx Server Configuration for History Mode Source: https://v3.router.vuejs.org/guide/essentials/history-mode Nginx configuration to use try_files to serve index.html for requests that do not match existing files or directories, supporting history mode. ```nginx location / { try_files $uri $uri/ /index.html; } ``` -------------------------------- ### Initial Navigation Callback Source: https://v3.router.vuejs.org/api Queue a callback to execute once the router completes its initial navigation. Useful for SSR to ensure consistent output. An optional error callback can handle initial route resolution errors. ```javascript router.onReady(callback, [errorCallback]) ``` -------------------------------- ### Caddy v2 Server Configuration for History Mode Source: https://v3.router.vuejs.org/guide/essentials/history-mode Caddy v2 configuration snippet to handle history mode by attempting to serve files directly and falling back to the root. ```caddy try_files {path} / ``` -------------------------------- ### Navigate using named routes or full paths with params Source: https://v3.router.vuejs.org/guide/essentials/navigation When using named routes with params, ensure you provide the route name or the full path. Providing a path with params directly might not work as expected. ```javascript const userId = '123' router.push({ name: 'user', params: { userId } }) // -> /user/123 ``` ```javascript const userId = '123' router.push({ path: `/user/${userId}` }) // -> /user/123 ``` ```javascript // This will NOT work router.push({ path: '/user', params: { userId } }) // -> /user ``` -------------------------------- ### Route Configuration with Named Views Source: https://v3.router.vuejs.org/guide/essentials/named-views Configure routes to render specific components into named router-view outlets using the `components` option. ```javascript const router = new VueRouter({ routes: [ { path: '/', components: { default: Foo, a: Bar, b: Baz } } ] }) ``` -------------------------------- ### Vue Router Catch-All Route for 404 Handling Source: https://v3.router.vuejs.org/guide/essentials/history-mode Implement a catch-all route in Vue Router to display a NotFoundComponent for any unmatched paths, addressing the caveat of history mode not reporting server 404s. ```javascript const router = new VueRouter({ mode: 'history', routes: [ { path: '/:catchAll(.*)', component: NotFoundComponent, name: 'NotFound' } ] }) ``` -------------------------------- ### Apache Server Configuration for History Mode Source: https://v3.router.vuejs.org/guide/essentials/history-mode Apache configuration using mod_rewrite to serve index.html for non-file and non-directory requests, enabling history mode. ```apache Options -MultiViews RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] ``` -------------------------------- ### Define Catch-all Route Source: https://v3.router.vuejs.org/guide/essentials/dynamic-matching Use an asterisk (*) in a route path to create a catch-all route, typically used for 404 Not Found pages. Ensure catch-all routes are defined last. ```javascript { // will match everything path: '*' } ``` ```javascript { // will match anything starting with /user- path: '/user-*' } ``` -------------------------------- ### Navigate through history stack with router.go Source: https://v3.router.vuejs.org/guide/essentials/navigation Use router.go to move forward or backward in the history stack by a specified number of steps. This method is similar to the browser's window.history.go() API. ```javascript // go forward by one record, the same as history.forward() router.go(1) ``` ```javascript // go back by one record, the same as history.back() router.go(-1) ``` ```javascript // go forward by 3 records router.go(3) ``` ```javascript // fails silently if there aren't that many records. router.go(-100) ``` ```javascript // fails silently if there aren't that many records. router.go(100) ``` -------------------------------- ### Register Global Before Guard Source: https://v3.router.vuejs.org/guide/advanced/navigation-guards Register a global before guard using `router.beforeEach`. This guard is called before each navigation. ```javascript const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ... }) ``` -------------------------------- ### Fetching Data After Navigation Source: https://v3.router.vuejs.org/guide/advanced/data-fetching Component logic for fetching post data after the component is created and handling route changes. Assumes a `getPost` function is available. ```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 } }) } } } ``` -------------------------------- ### Global Route Transitions Source: https://v3.router.vuejs.org/guide/advanced/transitions Apply a consistent transition to all routes by wrapping the `` component with a single `` component. ```html ``` -------------------------------- ### Native Node.js Server Configuration for History Mode Source: https://v3.router.vuejs.org/guide/essentials/history-mode A basic Node.js HTTP server configuration that reads and serves index.html for all requests, suitable for history mode. ```javascript const http = require('http') const fs = require('fs') const httpPort = 80 http.createServer((req, res) => { fs.readFile('index.html', 'utf-8', (err, content) => { if (err) { console.log('We cannot open "index.html" file.') } res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }) res.end(content) }) }).listen(httpPort, () => { console.log('Server listening on: http://localhost:%s', httpPort) }) ``` -------------------------------- ### Fetching Data Before Navigation Source: https://v3.router.vuejs.org/guide/advanced/data-fetching Component logic for fetching post data using route guards (`beforeRouteEnter` and `beforeRouteUpdate`). Assumes a `getPost` function is available. ```javascript export default { data () { return { post: null, error: null } }, beforeRouteEnter (to, from, next) { getPost(to.params.id, (err, post) => { next(vm => vm.setData(err, post)) }) }, // when route changes and this component is already rendered, // the logic will be slightly different. beforeRouteUpdate (to, from, next) { this.post = null getPost(to.params.id, (err, post) => { this.setData(err, post) next() }) }, methods: { setData (err, post) { if (err) { this.error = err.toString() } else { this.post = post } } } } ``` -------------------------------- ### Combine Async Component and Dynamic Import Source: https://v3.router.vuejs.org/guide/advanced/lazy-loading Combine the async component factory with dynamic import to create a component that is automatically code-split by webpack. ```javascript const Foo = () => import('./Foo.vue') ``` -------------------------------- ### Accessing Component Instance in beforeRouteEnter Source: https://v3.router.vuejs.org/guide/advanced/navigation-guards Demonstrates how to access the component instance in `beforeRouteEnter` by passing a callback to `next`. This callback is executed after navigation confirmation. ```javascript beforeRouteEnter (to, from, next) { next(vm => { // access to component instance via `vm` }) } ``` -------------------------------- ### router.app Source: https://v3.router.vuejs.org/api The root Vue instance into which the router was injected. ```APIDOC ## router.app ### Description The root Vue instance into which the router was injected. ### Type `Vue instance` ``` -------------------------------- ### Programmatically Navigate to a Named Route Source: https://v3.router.vuejs.org/guide/essentials/named-routes Perform navigation to a named route with parameters using the `router.push()` method. This is useful for imperative navigation triggered by events or logic. ```javascript router.push({ name: 'user', params: { userId: 123 } }) ``` -------------------------------- ### Exact Path Match Prop for Router Link Source: https://v3.router.vuejs.org/api The `exact-path` prop allows matching only the path section of the URL, ignoring query and hash parameters. This link will be active for variations like `/search?page=2` or `/search#filters`. ```html ``` -------------------------------- ### router.beforeEach / router.beforeResolve / router.afterEach Source: https://v3.router.vuejs.org/api Adds global navigation guards that are executed before, during, or after route resolution. Each method returns a function to remove the registered guard. ```APIDOC ## router.beforeEach / router.beforeResolve / router.afterEach ### Description Adds global navigation guards that are executed before, during, or after route resolution. Each method returns a function to remove the registered guard. ### Signatures ```javascript router.beforeEach((to, from, next) => { /* must call `next` */ }) router.beforeResolve((to, from, next) => { /* must call `next` */ }) router.afterEach((to, from) => {}) ``` ``` -------------------------------- ### Caddy v1 Server Configuration for History Mode Source: https://v3.router.vuejs.org/guide/essentials/history-mode Caddy v1 configuration snippet for history mode, rewriting all requests to the root path. ```caddy rewrite { regexp .* to {path} / } ``` -------------------------------- ### Firebase Hosting Configuration for History Mode Source: https://v3.router.vuejs.org/guide/essentials/history-mode Firebase hosting configuration in firebase.json to set up rewrites for history mode, directing all routes to index.html. ```json { "hosting": { "public": "dist", "rewrites": [ { "source": "**", "destination": "/index.html" } ] } } ``` -------------------------------- ### Basic Redirect to a Path Source: https://v3.router.vuejs.org/guide/essentials/redirect-and-alias Use this to redirect traffic from one path to another. The URL in the browser will be updated to the target path. ```javascript const router = new VueRouter({ routes: [ { path: '/a', redirect: '/b' } ] }) ``` -------------------------------- ### Exact Match Prop for Router Link Source: https://v3.router.vuejs.org/api Use the `exact` prop on a `` to force it into 'exact match mode'. This ensures the link is only active when the current path precisely matches the `to` prop. ```html ``` -------------------------------- ### Router Instance Injection Source: https://v3.router.vuejs.org/api Shows how the router instance is injected into child components as `this.$router` and the current route as `this.$route`. ```javascript this.$router this.$route ``` -------------------------------- ### Basic Scroll Behavior Function Source: https://v3.router.vuejs.org/guide/advanced/scroll-behavior Provide a scrollBehavior function when creating the router instance to control scrolling on navigation. ```javascript const router = new VueRouter({ routes: [...], scrollBehavior (to, from, savedPosition) { // return desired position } }) ``` -------------------------------- ### Nested Route Configuration with Named Views Source: https://v3.router.vuejs.org/guide/essentials/named-views Configure nested routes that utilize named views, mapping components to both the default and named outlets within child routes. ```javascript { path: '/settings', // You could also have named views at the top component: UserSettings, children: [{ path: 'emails', component: UserEmailsSubscriptions }, { path: 'profile', components: { default: UserProfile, helper: UserProfilePreview } }] } ``` -------------------------------- ### Add Routes Dynamically (Deprecated) Source: https://v3.router.vuejs.org/api Dynamically add routes using the deprecated `addRoutes` method. It accepts an array of route configurations. ```javascript router.addRoutes(routes: Array) ``` -------------------------------- ### Dynamic Import for Code Splitting Source: https://v3.router.vuejs.org/guide/advanced/lazy-loading Use webpack's dynamic import syntax to indicate a code-split point. This returns a Promise that resolves to the module. ```javascript import('./Foo.vue') // returns a Promise ``` -------------------------------- ### router.getMatchedComponents Source: https://v3.router.vuejs.org/api Returns an array of matched component definitions for a given location or the current route. Primarily used for server-side data prefetching. ```APIDOC ## router.getMatchedComponents ### Description Returns an array of matched component definitions for a given location or the current route. Primarily used for server-side data prefetching. ### Signature ```javascript const matchedComponents: Array = router.getMatchedComponents(location?) ``` ``` -------------------------------- ### Dynamic Redirect with a Function Source: https://v3.router.vuejs.org/guide/essentials/redirect-and-alias Implement dynamic redirects based on logic within a function. The function receives the target route and should return the redirect path or location. Navigation guards are not applied to the redirecting route itself. ```javascript const router = new VueRouter({ routes: [ { path: '/a', redirect: to => { // the function receives the target route as the argument // return redirect path/location here. }} ] }) ``` -------------------------------- ### IIS Server Configuration for History Mode Source: https://v3.router.vuejs.org/guide/essentials/history-mode IIS web.config file to configure URL rewriting for history mode, ensuring that requests for non-existent files or directories are rewritten to the root index.html. ```xml ``` -------------------------------- ### Default Nested Route Configuration Source: https://v3.router.vuejs.org/guide/essentials/nested-routes Configures an empty path for a child route, making UserHome render inside User's router-view when '/user/:id' is matched. ```javascript const router = new VueRouter({ routes: [ { path: '/user/:id', component: User, children: [ // UserHome will be rendered inside User's // when /user/:id is matched { path: '', component: UserHome } // ...other sub routes ] } ] }) ``` -------------------------------- ### Multiple Router Views Source: https://v3.router.vuejs.org/guide/essentials/named-views Define multiple named router-view components within a template to create distinct content areas. ```html ``` -------------------------------- ### Link to a Named Route with Parameters Source: https://v3.router.vuejs.org/guide/essentials/named-routes Use the `router-link` component with a `to` prop object specifying the route's name and any required parameters. This allows for declarative navigation in templates. ```html User ``` -------------------------------- ### Define Per-Route BeforeEnter Guard Source: https://v3.router.vuejs.org/guide/advanced/navigation-guards Define a `beforeEnter` guard directly on a route's configuration object. This guard has the same signature as global before guards. ```javascript const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, beforeEnter: (to, from, next) => { // ... } } ] }) ``` -------------------------------- ### Per-Route Component Transitions Source: https://v3.router.vuejs.org/guide/advanced/transitions Define unique transitions for each route's component by using named `` components within the route component's template. ```javascript const Foo = { template: `
...
` } const Bar = { template: `
...
` } ``` -------------------------------- ### Post Component Template Source: https://v3.router.vuejs.org/guide/advanced/data-fetching Template for a Post component that displays loading, error, or content based on fetched data. ```html ``` -------------------------------- ### Scroll Behavior Navigation Arguments Source: https://v3.router.vuejs.org/api Illustrates the 'to' and 'from' route objects provided to the scrollBehavior function, along with the savedPosition. ```javascript const router = new VueRouter({ scrollBehavior(to, from, savedPosition) { // `to` and `from` are both route objects } }) ``` -------------------------------- ### Component Enabled Options Source: https://v3.router.vuejs.org/api Options that can be enabled within components to control navigation. These include `beforeRouteEnter`, `beforeRouteUpdate`, and `beforeRouteLeave` guards, which allow for logic execution before, during, or after route changes. ```APIDOC ## Component Enabled Options ### Description These options can be enabled within components to control navigation behavior. ### Options - **beforeRouteEnter** - **beforeRouteUpdate** - **beforeRouteLeave** See In Component Guards. ``` -------------------------------- ### Navigate to a different URL with router.push Source: https://v3.router.vuejs.org/guide/essentials/navigation Use router.push to navigate to a different URL by pushing a new entry into the history stack. The argument can be a string path or a location descriptor object. ```javascript router.push('home') ``` ```javascript router.push({ path: 'home' }) ``` ```javascript router.push({ name: 'user', params: { userId: '123' } }) ``` ```javascript router.push({ path: 'register', query: { plan: 'private' } }) ``` -------------------------------- ### Using `this` in beforeRouteUpdate Source: https://v3.router.vuejs.org/guide/advanced/navigation-guards Shows how to directly use `this` within the `beforeRouteUpdate` guard to access component properties and call `next()` to proceed. ```javascript beforeRouteUpdate (to, from, next) { // just use `this` this.name = to.params.name next() } ``` -------------------------------- ### fallback Source: https://v3.router.vuejs.org/api Controls fallback to hash mode when history.pushState is not supported. Defaults to true. ```APIDOC ## fallback ### Description Controls fallback to hash mode when history.pushState is not supported. Defaults to true. ### Type `boolean` ### Default `true` ``` -------------------------------- ### Preventing Navigation with beforeRouteLeave Source: https://v3.router.vuejs.org/guide/advanced/navigation-guards Illustrates using the `beforeRouteLeave` guard to prompt the user before leaving a route, allowing navigation to be canceled by calling `next(false)`. ```javascript beforeRouteLeave (to, from, next) { const answer = window.confirm('Do you really want to leave? you have unsaved changes!') if (answer) { next() } else { next(false) } } ``` -------------------------------- ### Nested Route Configuration with Children Source: https://v3.router.vuejs.org/guide/essentials/nested-routes Defines nested routes for 'profile' and 'posts' under the '/user/:id' path, rendering into the User component's nested router-view. ```javascript const router = new VueRouter({ routes: [ { path: '/user/:id', component: User, children: [ { // UserProfile will be rendered inside User's // when /user/:id/profile is matched path: 'profile', component: UserProfile }, { // UserPosts will be rendered inside User's // when /user/:id/posts is matched path: 'posts', component: UserPosts } ] } ] }) ``` -------------------------------- ### Dynamic Route Transitions Source: https://v3.router.vuejs.org/guide/advanced/transitions Dynamically set the transition name based on route changes by watching the `$route` object and updating a transition name property. ```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' } } ``` -------------------------------- ### Route Alias Configuration Source: https://v3.router.vuejs.org/guide/essentials/redirect-and-alias Configure an alias to map multiple URLs to the same route component. When a user visits an aliased URL, the URL remains the same, but the route is matched as if the original path was visited. This provides flexibility in URL structure. ```javascript const router = new VueRouter({ routes: [ { path: '/a', component: A, alias: '/b' } ] }) ``` -------------------------------- ### Smooth Scrolling to Anchor Source: https://v3.router.vuejs.org/guide/advanced/scroll-behavior Enable native smooth scrolling when navigating to an anchor by adding the 'behavior: "smooth"' option. ```javascript scrollBehavior (to, from, savedPosition) { if (to.hash) { return { selector: to.hash, behavior: 'smooth', } } } ``` -------------------------------- ### Global Navigation Guards Source: https://v3.router.vuejs.org/api Register global navigation guards using `beforeEach`, `beforeResolve`, or `afterEach`. Each method returns a function to remove the registered guard. ```javascript router.beforeEach((to, from, next) => { /* must call `next` */ }) ``` ```javascript router.beforeResolve((to, from, next) => { /* must call `next` */ }) ``` ```javascript router.afterEach((to, from) => {}) ``` -------------------------------- ### router.mode Source: https://v3.router.vuejs.org/api The current mode the router is using (e.g., 'history', 'hash'). ```APIDOC ## router.mode ### Description The current mode the router is using (e.g., 'history', 'hash'). ### Type `string` ``` -------------------------------- ### Define Dynamic Route Segment Source: https://v3.router.vuejs.org/guide/essentials/dynamic-matching Use a colon (:) to define dynamic segments in your route paths. This allows a single route to match multiple URLs. ```javascript const User = { template: '
User
' } const router = new VueRouter({ routes: [ // dynamic segments start with a colon { path: '/user/:id', component: User } ] }) ``` -------------------------------- ### router.addRoutes Source: https://v3.router.vuejs.org/api Dynamically adds routes to the router. This method is deprecated; use `router.addRoute()` instead. ```APIDOC ## router.addRoutes (DEPRECATED) ### Description Dynamically adds routes to the router. This method is deprecated; use `router.addRoute()` instead. ### Signature ```javascript router.addRoutes(routes: Array) ``` ``` -------------------------------- ### Register Global After Hook Source: https://v3.router.vuejs.org/guide/advanced/navigation-guards Register a global after hook using `router.afterEach`. These hooks are called after navigation is confirmed and cannot affect the navigation process. ```javascript router.afterEach((to, from) => { // ... }) ``` -------------------------------- ### parseQuery / stringifyQuery Source: https://v3.router.vuejs.org/api Allows overriding the default query string parsing and stringifying functions. ```APIDOC ## parseQuery / stringifyQuery ### Description Allows overriding the default query string parsing and stringifying functions. ### Type `Function` ``` -------------------------------- ### Define an Async Component Source: https://v3.router.vuejs.org/guide/advanced/lazy-loading An async component can be defined as a factory function that returns a Promise resolving to the component definition. ```javascript const Foo = () => Promise.resolve({ /* component definition */ }) ``` -------------------------------- ### Access Catch-all PathMatch Parameter Source: https://v3.router.vuejs.org/guide/essentials/dynamic-matching When using an asterisk (*) route, a pathMatch parameter is automatically added to $route.params, containing the matched portion of the URL. ```javascript // Given a route { path: '/user-*' } this.$router.push('/user-admin') this.$route.params.pathMatch // 'admin' ``` ```javascript // Given a route { path: '*' } this.$router.push('/non-existing') this.$route.params.pathMatch // '/non-existing' ``` -------------------------------- ### Scroll to Anchor Source: https://v3.router.vuejs.org/guide/advanced/scroll-behavior Implement 'scroll to anchor' behavior by using the route's hash to specify a selector. ```javascript scrollBehavior (to, from, savedPosition) { if (to.hash) { return { selector: to.hash // , offset: { x: 0, y: 10 } } } } ``` -------------------------------- ### User Component with Nested Router-View Source: https://v3.router.vuejs.org/guide/essentials/nested-routes The User component template includes a nested `` to render child components. ```javascript const User = { template: `

User {{ $route.params.id }}

` } ``` -------------------------------- ### Accessing Router and Route in Components Source: https://v3.router.vuejs.org/guide Access the router instance as `this.$router` and the current route as `this.$route` within any Vue component. Use `this.$router.go()` for navigation. ```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('/') } } } ``` -------------------------------- ### router.currentRoute Source: https://v3.router.vuejs.org/api The current route object representing the active route. ```APIDOC ## router.currentRoute ### Description The current route object representing the active route. ### Type `Route` ``` -------------------------------- ### Replace the current history entry with router.replace Source: https://v3.router.vuejs.org/guide/essentials/navigation Use router.replace to navigate without pushing a new history entry, effectively replacing the current one. This is the programmatic equivalent of using the 'replace' attribute on router-link. ```javascript router.replace('/home') ``` -------------------------------- ### Async Scroll Behavior Source: https://v3.router.vuejs.org/guide/advanced/scroll-behavior Return a Promise that resolves to the desired scroll position for asynchronous scrolling, useful for animations or delays. ```javascript scrollBehavior (to, from, savedPosition) { return new Promise((resolve, reject) => { setTimeout(() => { resolve({ x: 0, y: 0 }) }, 500) }) } ``` -------------------------------- ### Use Lazy Loaded Component in Route Config Source: https://v3.router.vuejs.org/guide/advanced/lazy-loading No changes are needed in the route configuration; simply use the lazily loaded component as usual. ```javascript const router = new VueRouter({ routes: [{ path: '/foo', component: Foo }] }) ``` -------------------------------- ### router-view Props Source: https://v3.router.vuejs.org/api Props available for the router-view component, primarily for named views. ```APIDOC ## Props ### # name * type: `string` * default: `"default"` When a `` has a name, it will render the component with the corresponding name in the matched route record's `components` option. ``` -------------------------------- ### Accessing Navigation Failure Properties Source: https://v3.router.vuejs.org/guide/advanced/navigation-failures Navigation failures expose `to` and `from` properties, representing the target and current route locations respectively. This allows you to inspect the details of the failed navigation. ```javascript // trying to access the admin page router.push('/admin').catch(failure => { if (isNavigationFailure(failure, NavigationFailureType.redirected)) { failure.to.path // '/admin' failure.from.path // '/' } }) ``` -------------------------------- ### Define a Named Route Source: https://v3.router.vuejs.org/guide/essentials/named-routes Define a route with a specific name in the `routes` array when creating the VueRouter instance. This name can then be used for navigation. ```javascript const router = new VueRouter({ routes: [ { path: '/user/:userId', name: 'user', component: User } ] }) ``` -------------------------------- ### React to Route Changes with Navigation Guard Source: https://v3.router.vuejs.org/guide/essentials/dynamic-matching Alternatively, use the beforeRouteUpdate navigation guard to react to changes in route parameters within the same component instance. Remember to call next(). ```javascript const User = { template: '...', beforeRouteUpdate(to, from, next) { // react to route changes... // don't forget to call next() } } ``` -------------------------------- ### Group Components in the Same Async Chunk Source: https://v3.router.vuejs.org/guide/advanced/lazy-loading Use webpack's named chunks with a special comment syntax to group components nested under the same route into a single async chunk. ```javascript const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue') const Bar = () => import(/* webpackChunkName: "group-foo" */ './Bar.vue') const Baz = () => import(/* webpackChunkName: "group-foo" */ './Baz.vue') ``` -------------------------------- ### Nested Router Views in Template Source: https://v3.router.vuejs.org/guide/essentials/named-views Use nested router-view components, including named ones, within a parent component's template to build complex layouts. ```html

User Settings

``` -------------------------------- ### Accessing Meta Fields in Navigation Guards Source: https://v3.router.vuejs.org/guide/advanced/meta Check for meta fields in route records within global navigation guards. Use `$route.matched.some()` to iterate through matched route records and access their meta properties. ```javascript router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.requiresAuth)) { // this route requires auth, check if logged in // if not, redirect to login page. if (!auth.loggedIn()) { next({ path: '/login', query: { redirect: to.fullPath } }) } else { next() } } else { next() // make sure to always call next()! } }) ```