I am migrating an existing polymer-based application to Polymer 2, and one thing: the Polymer 2 upgrade guide is annoyingly silent about how to update the routing code to work with the updated app-routeand its entire “routing encapsulation” system.
With Starter Kit 1, we had a function page(), so the event handler that wanted to change the current route just started page("/new_page").
In Polymer 2, I found several different approaches to changing the route:
1. Create a custom event handling setup for your application:
home
<app-location route="{{route}}"></app-location>
<app-route route="{{route}}" pattern="/:page" ...></app-route>
...
ready() {
super.ready();
window.addEventListener('change-route', e => this.set('route.path', e.detail));
}
...
View
...
handleGoToOtherPage() {
window.dispatchEvent(new CustomEvent('change-route', { detail: '/new_page' }));
}
...
Cons: This is really cumbersome, especially dispatching events.
2. Use the JavaScript History API
( app-route)
...
handleGoToOtherPage() {
window.history.pushState({}, null, '/new_page');
window.dispatchEvent(new CustomEvent('location-changed'));
}
...
: pushState(), , app-location , " ", . , , 1, , , .
3. <iron-location>
...
<iron-location id="location"></iron-location>
...
handleGoToOtherPage() {
this.$.location.path = '/new_page';
}
...
: path, query hash , , . , ...
(tm)?
, ?