0
# Router Instance
1
2
Core router functionality for navigation, route matching, and configuration management. The VueRouter class is the main entry point for all routing operations.
3
4
## Capabilities
5
6
### VueRouter Constructor
7
8
Creates a new router instance with the provided configuration.
9
10
```javascript { .api }
11
/**
12
* Creates a new router instance
13
* @param options - Router configuration options
14
*/
15
constructor(options?: RouterOptions);
16
17
interface RouterOptions {
18
routes?: RouteConfig[];
19
mode?: 'hash' | 'history' | 'abstract';
20
base?: string;
21
fallback?: boolean;
22
linkActiveClass?: string;
23
linkExactActiveClass?: string;
24
parseQuery?: (query: string) => Object;
25
stringifyQuery?: (query: Object) => string;
26
scrollBehavior?: (to: Route, from: Route, savedPosition?: Position) => PositionResult;
27
}
28
```
29
30
**Usage Example:**
31
32
```javascript
33
import VueRouter from 'vue-router';
34
35
const router = new VueRouter({
36
mode: 'history',
37
base: '/app/',
38
routes: [
39
{ path: '/', component: Home },
40
{ path: '/about', component: About }
41
],
42
scrollBehavior(to, from, savedPosition) {
43
if (savedPosition) {
44
return savedPosition;
45
}
46
return { x: 0, y: 0 };
47
}
48
});
49
```
50
51
### Instance Properties
52
53
Access current router state and configuration.
54
55
```javascript { .api }
56
/**
57
* Current Vue app instance
58
*/
59
app: Vue;
60
61
/**
62
* Original options object passed to create the Router
63
*/
64
options: RouterOptions;
65
66
/**
67
* Configured mode when creating the Router instance
68
*/
69
mode: 'hash' | 'history' | 'abstract';
70
71
/**
72
* Current active Route object
73
*/
74
currentRoute: Route;
75
```
76
77
### Static Properties
78
79
Access VueRouter class-level utilities and constants.
80
81
```javascript { .api }
82
/**
83
* Vue plugin install function
84
*/
85
static install: PluginFunction<never>;
86
87
/**
88
* Vue Router version string
89
*/
90
static version: string;
91
92
/**
93
* Utility function to check if error is navigation failure
94
*/
95
static isNavigationFailure: typeof isNavigationFailure;
96
97
/**
98
* Navigation failure type enum for checking specific failure types
99
*/
100
static NavigationFailureType: {
101
[k in keyof typeof NavigationFailureType]: NavigationFailureType
102
};
103
104
/**
105
* Initial route location object
106
*/
107
static START_LOCATION: Route;
108
```
109
110
**Usage Examples:**
111
112
```javascript
113
// Check Vue Router version
114
console.log(VueRouter.version); // "3.6.5"
115
116
// Check for navigation failures
117
router.push('/some-route').catch(error => {
118
if (VueRouter.isNavigationFailure(error, VueRouter.NavigationFailureType.aborted)) {
119
console.log('Navigation was aborted');
120
}
121
});
122
123
// Access initial route
124
console.log(VueRouter.START_LOCATION); // Initial route object
125
126
// Plugin installation (done automatically with Vue.use())
127
Vue.use(VueRouter); // Calls VueRouter.install internally
128
```
129
130
### Programmatic Navigation
131
132
Navigate programmatically using router methods.
133
134
```javascript { .api }
135
/**
136
* Navigate to a new URL by pushing an entry in the history stack
137
* @param location - Route location to navigate to
138
* @returns Promise that resolves to the destination route
139
*/
140
push(location: RawLocation): Promise<Route>;
141
142
/**
143
* Navigate with callback functions (legacy)
144
* @param location - Route location to navigate to
145
* @param onComplete - Success callback
146
* @param onAbort - Error/abort callback
147
*/
148
push(location: RawLocation, onComplete?: (route: Route) => void, onAbort?: ErrorHandler): void;
149
150
/**
151
* Navigate by replacing the current entry in the history stack
152
* @param location - Route location to navigate to
153
* @returns Promise that resolves to the destination route
154
*/
155
replace(location: RawLocation): Promise<Route>;
156
157
/**
158
* Navigate with callback functions (legacy)
159
* @param location - Route location to navigate to
160
* @param onComplete - Success callback
161
* @param onAbort - Error/abort callback
162
*/
163
replace(location: RawLocation, onComplete?: (route: Route) => void, onAbort?: ErrorHandler): void;
164
165
/**
166
* Move forward or backward through the history
167
* @param n - Number of steps to move (positive = forward, negative = backward)
168
*/
169
go(n: number): void;
170
171
/**
172
* Go back one step in history
173
*/
174
back(): void;
175
176
/**
177
* Go forward one step in history
178
*/
179
forward(): void;
180
```
181
182
**Usage Examples:**
183
184
```javascript
185
// Navigate to a new route
186
router.push('/users/123');
187
router.push({ name: 'user', params: { id: '123' }});
188
router.push({ path: '/users/123', query: { tab: 'profile' }});
189
190
// Replace current route
191
router.replace('/login');
192
193
// History navigation
194
router.go(-1); // Go back one page
195
router.back(); // Same as go(-1)
196
router.forward(); // Same as go(1)
197
198
// Using promises
199
router.push('/users').then(route => {
200
console.log('Navigation completed', route);
201
}).catch(error => {
202
console.log('Navigation failed', error);
203
});
204
```
205
206
### Route Resolution and Matching
207
208
Resolve and match routes programmatically.
209
210
```javascript { .api }
211
/**
212
* Resolve a route location to a route object
213
* @param to - Route location to resolve
214
* @param current - Current route (defaults to currentRoute)
215
* @param append - Whether to append to current path
216
* @returns Resolved route information
217
*/
218
resolve(to: RawLocation, current?: Route, append?: boolean): {
219
location: Location;
220
route: Route;
221
href: string;
222
normalizedTo: Location;
223
resolved: Route;
224
};
225
226
/**
227
* Match a raw location against current routes
228
* @param raw - Raw location to match
229
* @param current - Current route context
230
* @param redirectedFrom - Original location if redirected
231
* @returns Matched route object
232
*/
233
match(raw: RawLocation, current?: Route, redirectedFrom?: Location): Route;
234
235
/**
236
* Get all components that match a given route
237
* @param to - Route to get components for (defaults to current route)
238
* @returns Array of matched components
239
*/
240
getMatchedComponents(to?: RawLocation | Route): Component[];
241
```
242
243
**Usage Examples:**
244
245
```javascript
246
// Resolve a route location
247
const resolved = router.resolve('/users/123');
248
console.log(resolved.href); // "/users/123"
249
console.log(resolved.route.params); // { id: '123' }
250
251
// Match a route
252
const route = router.match('/users/123');
253
console.log(route.matched); // Array of matched route records
254
255
// Get components for current route
256
const components = router.getMatchedComponents();
257
```
258
259
### Route Management
260
261
Add and manage routes dynamically.
262
263
```javascript { .api }
264
/**
265
* Add a new route record to the router
266
* @param route - Route configuration to add
267
*/
268
addRoute(route: RouteConfig): void;
269
270
/**
271
* Add a new route record as child of existing route
272
* @param parentName - Name of parent route
273
* @param route - Child route configuration to add
274
*/
275
addRoute(parentName: string, route: RouteConfig): void;
276
277
/**
278
* Add multiple routes (deprecated - use addRoute instead)
279
* @param routes - Array of route configurations
280
*/
281
addRoutes(routes: RouteConfig[]): void;
282
283
/**
284
* Get list of all active route records
285
* @returns Array of all route records
286
*/
287
getRoutes(): RouteRecordPublic[];
288
```
289
290
**Usage Examples:**
291
292
```javascript
293
// Add a new route
294
router.addRoute({ path: '/new-page', component: NewPage });
295
296
// Add a child route
297
router.addRoute('parent-route', {
298
path: 'child',
299
component: ChildComponent
300
});
301
302
// Get all routes
303
const allRoutes = router.getRoutes();
304
console.log(allRoutes.length);
305
```
306
307
### Router Lifecycle
308
309
Handle router initialization and errors.
310
311
```javascript { .api }
312
/**
313
* Add callback to be called when router has completed initial navigation
314
* @param callback - Function to call when ready
315
* @param errorCallback - Function to call if initial navigation fails
316
*/
317
onReady(callback: () => void, errorCallback?: ErrorHandler): void;
318
319
/**
320
* Add global error handler for navigation errors
321
* @param handler - Error handler function
322
*/
323
onError(handler: ErrorHandler): void;
324
```
325
326
**Usage Examples:**
327
328
```javascript
329
// Wait for router to be ready
330
router.onReady(() => {
331
console.log('Router is ready');
332
// Safe to render app
333
}, (error) => {
334
console.error('Router failed to initialize', error);
335
});
336
337
// Handle navigation errors
338
router.onError((error) => {
339
console.error('Navigation error:', error);
340
});
341
```
342
343
## Types
344
345
```javascript { .api }
346
type ErrorHandler = (err: Error) => void;
347
348
type PluginFunction<T> = (Vue: any, options?: T) => void;
349
350
interface Position {
351
x: number;
352
y: number;
353
}
354
355
type PositionResult = Position | {
356
selector: string;
357
offset?: Position;
358
behavior?: ScrollBehavior;
359
} | void;
360
361
interface RouteRecordPublic {
362
path: string;
363
components: Dictionary<Component>;
364
instances: Dictionary<Vue>;
365
name?: string;
366
redirect?: RedirectOption;
367
meta: any;
368
beforeEnter?: NavigationGuard;
369
props: boolean | Object | RoutePropsFunction | Dictionary<boolean | Object | RoutePropsFunction>;
370
}
371
```