Defining Routes and Params: Core Concepts
Route records map locations to views
A route record pairs a path pattern with a component and optional metadata. Static paths such as /projects are straightforward. A dynamic segment begins with a colon, for example /projects/:projectId, and captures one segment from the URL as a route parameter. Parameters identify a resource within a path; query parameters usually express filters, pagination, or other optional view state. Both are user-controlled strings and must be validated before they are used as trusted identifiers.
Named routes give a record a stable name and allow navigation with a structured object instead of assembling a path string. This reduces errors from missing slashes or incorrect encoding and makes links less coupled to URL spelling. When a named route has dynamic segments, provide the matching params. Do not pass both a path and params and expect params to alter the path; choose one navigation representation.
Nested routes and layout ownership
Nested records represent a view hierarchy. A parent component renders shared layout and contains a child router-view; its children render inside that outlet. The parent may own a project navigation bar while child routes display overview, members, or settings content. A child with an empty path acts as the default view for the parent URL. Nested paths are relative to their parent unless written as an absolute path, so read the final URL as the composition of the records.
Nesting should mirror a real shared shell. If two views do not share layout or lifecycle, a flat route table can be easier to understand. Deeply nested records create multiple outlets and guard boundaries, so use them only when the interface benefits from that structure. Each router-view is an explicit rendering slot; a child record cannot appear unless the matched parent tree provides the outlet.
Params, props, and query state
The current route exposes params and query values. Params are commonly strings, even when they look numeric. Convert and validate them at the boundary before calling a service. A malformed id should lead to a not-found or validation state rather than being silently coerced to an unrelated value. Query values can be absent or repeated, so code should account for optional and array cases when a query key may occur more than once.
Route props can pass selected params into a view as ordinary component props. This reduces direct dependence on the router and makes the view easier to test or reuse. Use a mapping function when validation or transformation is needed, and keep its output type explicit. A component that calls useRoute everywhere is convenient for a route-specific page, but it couples data loading and rendering to URL structure. Choose the boundary based on reuse and testability rather than applying props mechanically.
Matching and fallback routes
Vue Router ranks route patterns by specificity, but route tables should still be readable and intentional. A catch-all route belongs at the edge of the map and should render a deliberate not-found view. Do not let a broad pattern swallow valid paths or turn a missing API route into a Vue page. A redirect record can canonicalize a retired URL, but preserve query and parameter semantics where they matter.
Route names should be unique and meaningful. They are identifiers used by code, tests, breadcrumbs, and navigation. Renaming a route can be a breaking change for every caller even if the visible path remains the same. Treat the route map as an application contract: it defines discoverable locations, how resource identifiers enter the UI, and which layout owns each view.
Defining Routes and Params: Practice
Define named and nested records
The example provides a project shell, a default overview, and a settings child. The project id is dynamic and passed to the view as a prop. The named records make navigation independent of handwritten path strings.
const routes = [
{
path: '/projects/:projectId',
name: 'project',
component: ProjectLayout,
props: true,
children: [
{ path: '', name: 'project-overview', component: ProjectOverview },
{ path: 'settings', name: 'project-settings', component: ProjectSettings },
],
},
{ path: '/:pathMatch(.*)*', name: 'not-found', component: NotFoundView },
]
router.push({ name: 'project-settings', params: { projectId: 'p-42' } })
ProjectLayout must include a router-view for the child record. ProjectOverview receives projectId as a prop because the parent record sets props: true. The application can test the overview as a regular component by providing a prop, without having to construct a router. If the id requires conversion or validation, replace the boolean props setting with a mapping function that handles the route value explicitly.
The catch-all is intentionally separate from the project records. It should be used only after no more specific route matches and should not replace server-side handling for API or static assets. Verify the installed Vue Router version's catch-all syntax when adapting legacy configurations; version changes can affect path matching and regular-expression syntax.
Navigate without string assembly
Use a named route and a params object for a resource URL. Route params should correspond to dynamic path segments, and the router handles encoding the value as part of navigation. For query filters, provide a query object separately. Avoid manually concatenating a user-provided value into a URL because reserved characters can change path structure and make links incorrect. Validate identifiers after matching as well, since syntactically valid path segments may not identify an existing record.
Use route props to define the component boundary. A route-level mapping can select just the inputs the page needs and normalize string params. This prevents a reusable view from knowing that its data came from a particular URL pattern. If the component truly represents a location and must react to query changes, using the route object directly can be simpler; document that dependency and test it through router navigation.
Verify nested behavior
Navigate directly to the parent path and confirm the default child appears. Navigate to the settings path and confirm the shared shell remains while the child outlet changes. Use Back and Forward to verify the expected history sequence. Try an unknown path and confirm the not-found view appears. Use a project id containing reserved characters through the named route and inspect the resulting URL and received prop.
Add a query filter such as page=2 and decide whether it should be preserved when navigating between project child routes. Query state often represents shareable view state; dropping it accidentally can reset pagination or filters. Add a test that makes this behavior explicit. A route definition is not complete until the component and navigation behavior agree about which params, query keys, and defaults are meaningful.
As an exercise, flatten the child routes and compare the result. If the project shell must stay mounted across overview and settings, nesting communicates that ownership naturally. If no shared layout or lifecycle exists, flat records may be easier. The goal is not maximum nesting; it is a route table whose structure predicts the rendered component tree.
Defining Routes and Params: Trade-offs and Interviews
Keep the URL contract explicit
A route table is more than a list of pages. It decides how resources are identified, which locations are shareable, how layouts compose, and which code callers use to navigate. Named routes reduce path-string duplication, but names become an internal API. Use consistent names and test important navigation flows so renames do not silently break menus, redirects, breadcrumbs, or deep links.
Keep path params, query state, and application state distinct. A path parameter such as projectId identifies a resource. Query values commonly encode optional filters, sorting, or pagination so the view can be bookmarked. Transient state such as an open tooltip usually belongs in component state rather than the URL. The boundary is a product decision: if users should share or restore the state, query encoding is often appropriate.
Validate route input
All route values originate outside the component and should be treated as untrusted input. A dynamic path segment can be absent, malformed, or syntactically valid but unauthorized. Validate shape before a service call, handle missing resources as not found, and enforce authorization on the server. Props mapping can normalize the route value, but normalization is not authorization.
Nested routes provide shared layout and view outlets. They also affect component reuse and lifecycle: changing only a child path can keep the parent mounted, which is usually desirable for persistent navigation and data. A deep route tree may make guards and error handling difficult to locate. Keep nesting aligned to ownership boundaries and give each layout outlet a clear purpose.
A catch-all route should produce a real not-found state. It should not disguise failures from APIs or missing assets, and broad fallback rules should be tested after deployment. Static routes, dynamic routes, and catch-alls should remain easy to distinguish during review, even though the matcher has its own specificity rules.
Testing route behavior
Test named navigation with realistic params, direct loading of nested routes, preservation of relevant query state, and unknown paths. Test that a parent outlet renders the default child and that route props have the expected type after mapping. Include malformed identifiers and a not-found result. A view unit test can stub props; a router integration test proves records and outlets fit together.
For user-facing navigation, verify links have descriptive text and preserve native anchor behavior. Active links should identify the current location accessibly. If a route is renamed or a path changes, consider bookmarks and external links, not just in-app callers. Redirects may preserve compatibility, but should not create loops or discard meaningful query values.
In an interview, explain how a path maps to a record, how dynamic params differ from query values, and how a parent outlet composes with a child. Discuss named navigation and route props as ways to control coupling. Finish with validation and server authorization boundaries. That answer shows the route map is a user-facing contract, not merely syntax for switching components. Mention how direct links, bookmarks, and redirects preserve that contract as the application evolves.
Quiz
1. Which statement about Defining Routes and Params is accurate?
2. When reviewing Defining Routes and Params, which point must hold?
3. What does a nested child route require from its parent component?
4. What is a benefit of navigating by a named route with params?
Flashcards
Question
What is Defining Routes and Params?
Click to reveal answer
Answer
Declare path patterns, named routes, and dynamic segments.
Question
Defining Routes and Params: why it matters
Click to reveal answer
Answer
A route record pairs a path pattern with the component that router-view should render.
Question
Defining Routes and Params: key detail
Click to reveal answer
Answer
Colon segments like users slash id capture dynamic values available as route params.
Question
Defining Routes and Params: practical note
Click to reveal answer
Answer
Named routes let you navigate by name with a params object instead of building strings.
Question
What does a nested route need in its parent view?
Click to reveal answer
Answer
A router-view outlet for the child component.
Revision Notes
Key Takeaways
- 1. A route record pairs a path pattern with the component that router-view should render.
- 2. Colon segments like users slash id capture dynamic values available as route params.
- 3. Named routes let you navigate by name with a params object instead of building strings.
Interview Tips
- • Explain Defining Routes and Params with one concrete example from real vue work, not a textbook restatement.
- • Discuss the trade-off: when Defining Routes and Params helps and when a lighter approach wins.
- • Place Defining Routes and Params inside the Routing with Vue Router phase — interviewers check that you see the progression, not isolated facts.
Cheat Sheet
Defining Routes and Params Cheat Sheet
Phase: Routing with Vue Router | Level: beginner
Key points:
- A route record pairs a path pattern with the component that router-view should render.
- Colon segments like users slash id capture dynamic values available as route params.
- Named routes let you navigate by name with a params object instead of building strings.
- Nested routes render children inside a parent route's router-view outlet.
Tags: vue, router, routes
Continue Learning
Before You Start
- No prerequisites listed.