我正在使用 Polymer Starter Kit,并希望将每条路线的内容放在单独的文件中(/pages/games.html、/pages/movies.html 等),但我找不到任何示例。
有人能指出我正确的方向吗?还是不可能或不推荐这样实现路由?
您可以通过很多不同的方式来解决这个问题(在构建时替换 index.html 中的持有者,换成不同的路由器)。一种这样的方法是实现您的文件,然后将它们 fetch() 到 DOM 中。这是 page.js 存储库中概述的部分示例中使用的一种方法。
因此,让我们在入门工具包中进行修改iron-pages
,index.html
使其具有加载部分:
<iron-pages attr-for-selected="data-route" selected="{{route}}">
<!-- Block we'll load our partials into -->
<section id="load" data-route="load"></section>
...
然后让我们修改elements/routing.html
以更改我们的page.js。让我们路由/test
到我们的目标负载部分:
window.addEventListener('WebComponentsReady', function() {
page('/test', function () {
// iron-pages needs to show the proper section
// in this case, our designated loading target
app.route = 'load';
// We include fetch.js polyfill in route.html for simplicity
// 1. bower install fetch
// 2. Add <script src="../../bower_components/fetch/fetch.js"></script> to routing.html
fetch('/pages/test.html')
.then(function(response) {
return response.text()
}).then(function(body) {
document.querySelector('#load').innerHTML = body;
});
});
...
然后,我们可以实现我们想要的任意数量的页面,routing.html
以便根据需要加载我们的 html 页面。
请注意,这种基本方法没有考虑缓存响应(后退/前进会再次触发请求,从性能的角度来看您可能不希望这样做),并且我们没有在上面的示例中捕获错误。但这是一种这样的方法。