URL Parameters
Route parameters are useful when the same Web Component needs to be rendered for multiple paths, where part of the path is static, and another part contains a parameter value.
For example, the paths /user/1
and /user/42
can both have the same route to render the content.
The /user/
part is static, and 1
and 42
are the parameter values.
Route parameters are defined using an express.js
-like syntax.
The implementation is based on the path-to-regexp
library, which is commonly used in modern frontend libraries and frameworks.
The following features are supported:
Named parameters:
/profile/:user
Optional parameters:
/:size/:color?
Zero-or-more segments:
/kb/:path*
One-or-more segments:
/kb/:path+
Custom parameter patterns:
/image-:size(\d+)px
Unnamed parameters:
/(user[s]?)/:id
Routes for these features can be defined as follows:
const router = new Router(document.getElementById('outlet'));
router.setRoutes([
{path: '/', component: 'x-home-view'},
{path: '/profile/:user', component: 'x-user-profile'},
{path: '/image/:size/:color?', component: 'x-image-view'},
{path: '/kb/:path*', component: 'x-knowledge-base'},
{path: '/image-:size(\\d+)px', component: 'x-image-view'},
{path: '/(user[s]?)/:id', component: 'x-profile-view'},
]);
Accessing Route Parameters
Route parameters can be accessed in the location.params
property of the route component.
The location
property is defined by the router.
Named parameters are accessible by a string key, such as
location.params.id
orlocation.params['id']
.Unnamed parameters are accessible by a numeric index, such as
location.params[0]
.
import { BeforeEnterObserver, Router, RouterLocation } from '@vaadin/router';
import { View } from '../../views/view';
@customElement('user-view')
export class CreateOrUpdatePetView extends View
implements BeforeEnterObserver { 1
@state() id?;
onBeforeEnter(location: RouterLocation) { 2
this.id = parseInt(location.params.id as string);
}
render(){
return html`
<h1>Viewing user with id ${this.id}</h1>
`;
}
}
Implement
BeforeEnterObserver
in your view. See the Navigation lifecycle article for a list of different lifecycle callbacks for views.Implement the
onBeforeEnter()
callback to read the parameter value.