Polymer:如何动态导入元素

iro*_*oyo 4 javascript web-component polymer

任何人都可以告诉我如何根据Polymer属性的值导入元素?我以为我可以使用数据绑定但是...它不起作用.是否可以动态导入元素?

代码示例:

<link rel="import" href="app-window/{{name}}-app.html"> 
//This was my first idea (obviously doesn't work)


<polymer-element name="window-base" attributes="name" >
    <template>
        <link rel="stylesheet" href="window-base.css">
        <section id="app">
            <!--here will go the instance-->
        </section>
    </template>
    <script>
        Polymer('window-base', {
            name: "Finder",
            ready: function () {
                this.instanceApp();
            },
            instanceApp: function () {
            //this depends on the import made
                var app=document.createElement(this.name + "-app");
                this.$.app.appendChild(app);    
            }
        });
    </script>
</polymer-element>
Run Code Online (Sandbox Code Playgroud)

谢谢!

小智 9

根据Polymer 1.0迁移指南:

全局Polymer.import函数由importHref替换.可以从this.importHref中的元素调用新方法.在元素外部,可以将其称为Polymer.Base.importHref.

所以...

this.importHref(["yourComponent.html"], function() {})
Run Code Online (Sandbox Code Playgroud)


jrm*_*erz 6

这是我用于动态导入元素的方法.我使用硫化机将我的元素分解为逻辑模块.然后我使用Polymer.import:

聚合物0.5

Polymer.import( ['/elements/'+this.module+'-module.html'], function() {
    console.log('/elements/'+this.module+'-module.html loaded');
    this.onComplete();
}.bind(this));
Run Code Online (Sandbox Code Playgroud)

更新Polymer 1.0

只需使用链接[rel ="import"]标记即可

var link = document.createElement('link');
link.setAttribute('rel', 'import');
link.setAttribute('href', 'elements/app-module.html');
document.body.appendChild(link)
Run Code Online (Sandbox Code Playgroud)