问题
Sup! Back button sometimes doesn't work with my polymer project. When i hit back button the page
variable is steel the current page and i need to hit the button twice or three times to get it working for example i go to the /#/rules
page from /#/home
but it doesn't go back to /#/home
once i press the back button the second or third time by the way it does go back to the main page. Here is my observer and router:
properties: {
page: {
type: String,
reflectToAttribute: true,
observer: '_pageChanged',
},
},
observers: [
'_routePageChanged(routeData.page)',
],
_routePageChanged: function (page) {
this.page = page || 'home';
this.set('route.path', `/${this.page}`);
},
_pageChanged: function (page) {
// Load page import on demand. Show 404 page if fails
var resolvedPageUrl = this.resolveUrl(page + '.html');
this.importHref(resolvedPageUrl, null, this._showPage404, true);
window.history.pushState({}, null, `#/${this.page}`);
},
And this is my app-route
element:
<app-route route="{{route}}" pattern="/:page" data="{{routeData}}" tail="{{subroute}}"></app-route>
Just can't figure out why it does not work the first time. Any help is appreciated and i have already searched a lot with no results.
回答1:
Can you try this, assuming you have <app-route route="{{route}}"></app-route>
?
observers: [
'_routePageChanged(route.path)',
],
_routePageChanged: function(path) {
if (path) {
this.page = this.routeData.page;
} else {
/*
* It's unnecessary to have the following line.
*/
// this.page = 'home';
this.set('route.path', '/home');
}
},
Why it works after all?
I learned my lesson by debugging the source code of <app-route>
. If the path is empty, the code for updating data
will be skipped - and your observer, _routePageChanged(routeData.page)
, won't be triggered. See
- https://github.com/PolymerElements/app-route/blob/master/app-route.html#L254-L257
- https://github.com/PolymerElements/app-route/blob/master/app-route.html#L320-L328
You may consider it to be a flaw in <app-route>
. Whatsoever, it's open source, and you can always find your way.
来源:https://stackoverflow.com/questions/45708702/polymer-back-button-doesnt-work-with-hash-routing