0
# Route Configuration
1
2
Route definition system supporting nested routes, dynamic parameters, route-level guards, and comprehensive configuration options for building complex routing structures.
3
4
## Capabilities
5
6
### Route Definition
7
8
Define routes with components, parameters, and metadata.
9
10
```javascript { .api }
11
/**
12
* Route configuration object defining a single route
13
*/
14
interface RouteConfig {
15
/** The path pattern for this route */
16
path: string;
17
/** Component to render for this route */
18
component?: Component;
19
/** Unique name for this route (enables named routing) */
20
name?: string;
21
/** Child routes for nested routing */
22
children?: RouteConfig[];
23
/** Redirect target when this route is matched */
24
redirect?: RedirectOption;
25
/** Alternative path(es) that should match this route */
26
alias?: string | string[];
27
/** Custom metadata attached to this route */
28
meta?: RouteMeta;
29
/** Route-level navigation guard */
30
beforeEnter?: NavigationGuard;
31
/** Whether path matching should be case sensitive */
32
caseSensitive?: boolean;
33
/** Options for path-to-regexp matching */
34
pathToRegexpOptions?: PathToRegexpOptions;
35
}
36
37
/**
38
* Multi-view route configuration with named components
39
*/
40
interface RouteConfigMultipleViews {
41
path: string;
42
/** Named components for multiple router-view outlets */
43
components?: Dictionary<Component>;
44
/** Props configuration for each named component */
45
props?: Dictionary<boolean | Object | RoutePropsFunction>;
46
name?: string;
47
children?: RouteConfig[];
48
redirect?: RedirectOption;
49
alias?: string | string[];
50
meta?: RouteMeta;
51
beforeEnter?: NavigationGuard;
52
caseSensitive?: boolean;
53
pathToRegexpOptions?: PathToRegexpOptions;
54
}
55
56
type RedirectOption = RawLocation | ((to: Route) => RawLocation);
57
type RoutePropsFunction = (route: Route) => Object;
58
```
59
60
**Usage Examples:**
61
62
```javascript
63
// Basic route configuration
64
const routes = [
65
// Static route
66
{ path: '/', component: Home },
67
68
// Route with parameters
69
{ path: '/user/:id', component: User, name: 'user' },
70
71
// Route with query and hash support
72
{ path: '/search', component: Search },
73
74
// Route with redirect
75
{ path: '/home', redirect: '/' },
76
77
// Route with alias
78
{ path: '/users', component: Users, alias: '/people' },
79
80
// Route with metadata
81
{
82
path: '/admin',
83
component: Admin,
84
meta: { requiresAuth: true, role: 'admin' }
85
}
86
];
87
```
88
89
### Nested Routes
90
91
Configure hierarchical route structures with parent and child relationships.
92
93
```javascript { .api }
94
/**
95
* Nested route configuration with parent-child relationships
96
*/
97
interface NestedRouteConfig extends RouteConfig {
98
children?: RouteConfig[];
99
}
100
```
101
102
**Usage Examples:**
103
104
```javascript
105
const routes = [
106
{
107
path: '/user/:id',
108
component: User,
109
children: [
110
// Empty path means /user/:id
111
{ path: '', component: UserHome },
112
113
// /user/:id/profile
114
{ path: 'profile', component: UserProfile },
115
116
// /user/:id/posts
117
{ path: 'posts', component: UserPosts },
118
119
// Nested parameters: /user/:id/post/:postId
120
{ path: 'post/:postId', component: UserPost }
121
]
122
}
123
];
124
```
125
126
### Dynamic Route Matching
127
128
Configure routes with dynamic segments, optional parameters, and pattern matching.
129
130
```javascript { .api }
131
/**
132
* Path-to-RegExp options for advanced pattern matching
133
*/
134
interface PathToRegexpOptions {
135
/** Case sensitive matching */
136
sensitive?: boolean;
137
/** Strict mode (disallow optional trailing delimiter) */
138
strict?: boolean;
139
/** End matching (pattern should end at end of string) */
140
end?: boolean;
141
}
142
```
143
144
**Usage Examples:**
145
146
```javascript
147
const routes = [
148
// Required parameter
149
{ path: '/user/:id', component: User },
150
151
// Optional parameter
152
{ path: '/user/:id?', component: User },
153
154
// Wildcard (catch-all)
155
{ path: '/product/*', component: Product },
156
157
// Multiple parameters
158
{ path: '/user/:id/post/:postId', component: Post },
159
160
// Parameter with regex pattern
161
{ path: '/user/:id(\\d+)', component: User }, // Only numeric IDs
162
163
// Advanced path-to-regexp options
164
{
165
path: '/case-sensitive',
166
component: Component,
167
pathToRegexpOptions: { sensitive: true }
168
}
169
];
170
```
171
172
### Route Props
173
174
Configure how route parameters are passed to components as props.
175
176
```javascript { .api }
177
/**
178
* Props configuration for passing route data to components
179
*/
180
interface RouteProps {
181
/** Boolean mode: pass all params as props */
182
props?: boolean;
183
/** Object mode: static props object */
184
props?: Object;
185
/** Function mode: dynamic props based on route */
186
props?: RoutePropsFunction;
187
/** Named views: props config for each named component */
188
props?: Dictionary<boolean | Object | RoutePropsFunction>;
189
}
190
191
type RoutePropsFunction = (route: Route) => Object;
192
```
193
194
**Usage Examples:**
195
196
```javascript
197
const routes = [
198
// Boolean mode - pass all route.params as props
199
{ path: '/user/:id', component: User, props: true },
200
201
// Object mode - static props
202
{
203
path: '/hello',
204
component: Hello,
205
props: { greeting: 'Hello World!' }
206
},
207
208
// Function mode - dynamic props
209
{
210
path: '/search',
211
component: Search,
212
props: (route) => ({
213
query: route.query.q,
214
page: parseInt(route.query.page) || 1
215
})
216
},
217
218
// Named views with different props
219
{
220
path: '/dashboard',
221
components: {
222
default: Dashboard,
223
sidebar: Sidebar
224
},
225
props: {
226
default: true,
227
sidebar: { collapsed: false }
228
}
229
}
230
];
231
```
232
233
### Route Metadata
234
235
Attach custom data to routes for use in navigation guards and components.
236
237
```javascript { .api }
238
/**
239
* Custom metadata object attached to routes
240
*/
241
interface RouteMeta extends Record<string | number | symbol, any> {}
242
```
243
244
**Usage Examples:**
245
246
```javascript
247
const routes = [
248
{
249
path: '/admin',
250
component: Admin,
251
meta: {
252
requiresAuth: true,
253
roles: ['admin', 'moderator'],
254
title: 'Admin Panel',
255
breadcrumb: 'Administration'
256
}
257
},
258
{
259
path: '/public',
260
component: Public,
261
meta: {
262
public: true,
263
analytics: { category: 'public-pages' }
264
}
265
}
266
];
267
268
// Access in components
269
export default {
270
created() {
271
console.log(this.$route.meta.title); // 'Admin Panel'
272
}
273
};
274
275
// Access in navigation guards
276
router.beforeEach((to, from, next) => {
277
if (to.meta.requiresAuth && !isAuthenticated()) {
278
next('/login');
279
} else {
280
next();
281
}
282
});
283
```
284
285
### Route-level Guards
286
287
Configure navigation guards that apply to specific routes.
288
289
```javascript { .api }
290
/**
291
* Route-level navigation guard
292
* @param to - Target route being navigated to
293
* @param from - Current route being navigated away from
294
* @param next - Function to call to continue navigation
295
*/
296
type NavigationGuard = (to: Route, from: Route, next: NavigationGuardNext) => any;
297
298
interface RouteGuardConfig {
299
beforeEnter?: NavigationGuard;
300
}
301
```
302
303
**Usage Examples:**
304
305
```javascript
306
const routes = [
307
{
308
path: '/admin',
309
component: Admin,
310
beforeEnter: (to, from, next) => {
311
// Check authentication
312
if (isAuthenticated() && hasAdminRole()) {
313
next(); // Allow access
314
} else {
315
next('/login'); // Redirect to login
316
}
317
}
318
},
319
{
320
path: '/user/:id',
321
component: UserProfile,
322
beforeEnter: async (to, from, next) => {
323
try {
324
// Validate user exists
325
await validateUser(to.params.id);
326
next();
327
} catch (error) {
328
next('/not-found');
329
}
330
}
331
}
332
];
333
```
334
335
### Router Configuration
336
337
Configure router-wide options and behavior.
338
339
```javascript { .api }
340
/**
341
* Router constructor options
342
*/
343
interface RouterOptions {
344
/** Array of route configurations */
345
routes?: RouteConfig[];
346
/** Routing mode */
347
mode?: 'hash' | 'history' | 'abstract';
348
/** Base URL for all routes */
349
base?: string;
350
/** Whether to fallback to hash mode when history is not supported */
351
fallback?: boolean;
352
/** Default active class for RouterLink */
353
linkActiveClass?: string;
354
/** Default exact active class for RouterLink */
355
linkExactActiveClass?: string;
356
/** Custom query string parser */
357
parseQuery?: (query: string) => Object;
358
/** Custom query string serializer */
359
stringifyQuery?: (query: Object) => string;
360
/** Scroll behavior handler */
361
scrollBehavior?: (to: Route, from: Route, savedPosition?: Position) => PositionResult;
362
}
363
```
364
365
**Usage Examples:**
366
367
```javascript
368
const router = new VueRouter({
369
mode: 'history',
370
base: '/my-app/',
371
routes,
372
373
// Custom link classes
374
linkActiveClass: 'is-active',
375
linkExactActiveClass: 'is-exact-active',
376
377
// Custom query handling
378
parseQuery(query) {
379
// Custom parsing logic
380
return customQueryParser(query);
381
},
382
383
stringifyQuery(obj) {
384
// Custom serialization logic
385
return customQuerySerializer(obj);
386
},
387
388
// Scroll behavior
389
scrollBehavior(to, from, savedPosition) {
390
if (savedPosition) {
391
return savedPosition;
392
}
393
if (to.hash) {
394
return { selector: to.hash };
395
}
396
return { x: 0, y: 0 };
397
}
398
});
399
```
400
401
## Types
402
403
```javascript { .api }
404
interface RouteRecord {
405
path: string;
406
regex: RegExp;
407
components: Dictionary<Component>;
408
instances: Dictionary<Vue>;
409
name?: string;
410
parent?: RouteRecord;
411
redirect?: RedirectOption;
412
matchAs?: string;
413
meta: RouteMeta;
414
beforeEnter?: NavigationGuard;
415
props: boolean | Object | RoutePropsFunction | Dictionary<boolean | Object | RoutePropsFunction>;
416
}
417
418
type Component = {} | Vue.Component | Vue.AsyncComponent;
419
type Dictionary<T> = { [key: string]: T };
420
421
interface Position {
422
x: number;
423
y: number;
424
}
425
426
type PositionResult = Position | {
427
selector: string;
428
offset?: Position;
429
behavior?: ScrollBehavior;
430
} | void;
431
```