这是我对您问题的解释,所以我不确定您是否可以。如果我误解了你,请发表评论,我很乐意更新我的答案。
我想出了一个简单的元素组合,不需要dom-repeat 或手动模板标记。该解决方案由两个自定义元素组成,即my-parent 和my-child。
两个自定义元素的定义如下:
<dom-module id="my-parent">
<template>
<tabs>
<content></content>
</tabs>
</template>
<script>
Polymer({
is: 'my-parent',
});
</script>
</dom-module>
<dom-module id="my-child">
<template>
<section>
<content></content>
</section>
</template>
<script>
Polymer({
is: 'my-child',
});
</script>
</dom-module>
它们的建议用法如下:
<my-parent>
<my-child>First tab</my-child>
<my-child>Second tab</my-child>
<my-child>Third tab</my-child>
</my-parent>
在线演示:http://jsbin.com/hibuzafapu/1/edit?html,output
生成的 HTML 代码如下所示:
<my-parent>
<tabs>
<my-child>
<section>
First tab
</section>
</my-child>
<my-child>
<section>
Second tab
</section>
</my-child>
<my-child>
<section>
Third tab
</section>
</my-child>
</tabs>
</my-parent>
如果我理解正确,那么只有包裹<section> 标记的<my-child> 标记是多余的。目前,前面提到的标签什么都不做,只是一个包裹所有东西的块级元素(就像div)。如果这让您感到困扰,那么您实际上可以省略 <section> 标签并将所有样式直接放在 <my-child> 标签上。
在这种情况下,生成的 HTML 将如下所示:
<my-parent>
<tabs>
<my-child>
First tab
</my-child>
<my-child>
Second tab
</my-child>
<my-child>
Third tab
</my-child>
</tabs>
</my-parent>
更新
为了给解决方案添加一些动态(添加/删除选项卡),您有两种选择:使用dom-repeat 并在 light DOM 中标记项目,或者将项目数组推入 my-parent 元素并使用 @ 987654339@那里。这两个选项在实现上非常相似,并且它们的工作方式没有太大区别。
选项 A:在 light DOM 中标记:
两个自定义元素的定义保持不变,唯一的区别是您如何使用它们。与其对 light DOM 进行硬编码,不如让它更具动态性。
<dom-module is="tmp-element">
<template>
<my-parent>
<template is="dom-repeat" items="[[myItems]]">
<my-child>[[item.content]]</my-child>
</template>
</my-parent>
</template>
<script>
Polymer({
is: 'tmp-element',
ready: function() {
this.myItems = [
{ content: "First tab" },
{ content: "Second tab" },
{ content: "Third tab" },
],
};
});
</script>
</dom-module>
<tmp-element></tmp-element>
tmp-element 纯粹用于创建绑定范围并将数据提供给dom-repeat。
现场演示:http://jsbin.com/gafisuwege/1/edit?html,console,outputenter link description here
选项 B:在父级内部标记:
在此选项中,父项需要有一个附加属性,我们将在其中提供项目数组。
my-parent 元素的新版本如下:
<dom-module id="my-parent">
<template>
<tabs>
<template is="dom-repeat" items="[[items]]">
<my-child>[[item.content]]</my-child>
</template>
</tabs>
</template>
<script>
Polymer({
is: 'my-parent',
properties: {
items: Array,
},
});
</script>
</dom-module>
而用法是:
<dom-module is="tmp-element">
<template>
<my-parent items="[[myItems]]"></my-parent>
</template>
<script>
Polymer({
is: 'tmp-element',
ready: function() {
this.myItems = [
{ content: "First tab" },
{ content: "Second tab" },
{ content: "Third tab" },
];
},
});
</script>
</dom-module>
<tmp-element></tmp-element>
在这里,我还使用了tmp-element(与以前不同)来提供my-parent 的数据。
现场演示:http://jsbin.com/kiwidaqeki/1/edit?html,console,output