我一直坚持在 Polymer 3 中实现路由。我遵循了应用程序路由文档。但是在加载网页时,我没有看到任何组件被加载。我签到了shadow DOM
并且没有看到任何 DOM 被渲染。不知道我错过了什么。这是代码。
static get properties() {
return {
page:{
type: String,
reflectToAttribute: true,
observer: '_pageChanged'
}
};
}
_pageChanged(currentPage, oldPage){
console.log('CURRENT - ', currentPage);
console.log('OLD - ', oldPage);
switch(currentPage){
case 'home':
import('./home-comp.js').then()
break;
case 'about':
import('./about-comp.js').then()
break;
case 'contact':
import('./contact-comp.js').then()
break;
default:
this.page = 'home';
}
}
<app-route
route="{{route}}"
pattern="/:page"
data="{{routeData}}"
tail="{{subroute}}">
</app-route>
<home-comp name="home"></home-comp>
<about-comp name="about"></about-comp>
<contact-comp name="contact"></contact-comp>
我没有看到很多关于 Polymer 3 的文档可用于检查问题。在浏览了 Polymer 默认示例 Web 应用程序 shop. 后,我遇到了一些合适的解决方案。我想与社区分享它,供任何需要帮助的人使用。
你需要有
应用程序路由:用于实现路由
铁页:基本上是页面切换器按需加载所需的组件
在应用程序路由中,
/* observer: Its a simple observer (basically a watch which holds current value & old value) that triggers whenever data changed in page property. We read the observer and calls a function to grab its earlier */
static get properties() {
return {
page:{
type: String,
reflectToAttribute: true,
observer: '_pageChanged'
}
};
}
_pageChanged(currentPage, oldPage){
console.log('CURRENT - ', currentPage);
console.log('OLD - ', oldPage);
switch(currentPage){
case 'home':
import('./home-comp.js').then()
break;
case 'about':
import('./about-comp.js').then()
break;
case 'contact':
import('./contact-comp.js').then()
break;
default:
this.page = 'home';
}
}
<!-- pattern: reads the href property., hence set the page (pattern="/:page") property in static get property to read its data -->
<app-route route="{{route}}" pattern="/:page" data="{{routeData}}" tail="{{subroute}}"></app-route>
<ul>
<li>
<a href="/home">Home</a>
</li>
<li>
<a href="/about">About</a>
</li>
<li>
<a href="/contact">Contact</a>
</li>
</ul>
但是第一次加载时,页面属性没有任何值并抛出异常undefined
.
因此我们可以使用complex observer
观察此类变化
static get observers(){
return ['_routerChanged(routeData.page)'];
}
_routerChanged(page){
console.log('CHANGED PAGE - ', page);
this.page = page || 'home';
}
更改的路线数据不会加载组件,除非我们有iron-pages
。它基本上是一个按需组件切换器/加载器。将所有组件包裹在main-app
under <iron-pages>
<!-- selected: Data binding helps to get changed page value -->
<!-- attr-for-selected: It reads value of name attr defined in each component & matches with selected value and triggers page switch -->
<!-- fallback-selection: for 404., page/component not found handling -->
<iron-pages selected="[[page]]" attr-for-selected="name" selected-attribute="visible" fallback-selection="404">
<home-comp name="home"></home-comp>
<about-comp name="about"></about-comp>
<contact-comp name="contact"></contact-comp>
</iron-pages>
这是使用 app-route 在 Polymer 3 中实现路由的完整指南。希望这可以帮助点击这里
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)