我有一个嵌套的javascript对象数组,如下所示:
[
{id: 1, title: 'hello', parent: 0, children: [
{id: 3, title: 'hello', parent: 1, children: [
{id: 4, title: 'hello', parent: 3, children: [
{id: 5, title: 'hello', parent: 4},
{id: 6, title: 'hello', parent: 4}
]},
{id: 7, title: 'hello', parent: 3}
]}
]},
{id: 2, title: 'hello', parent: 0, children: [
{id: 8, title: 'hello', parent: 2}
]}
]
我试图找出如何定义聚合物元素的模板部分,该部分将呈现这样的嵌套列表,您不知道递归的深度。例如,我怎么能在模板中使用聚合物表达式来渲染这个递归对象?
<ul>
<li>hello (1)
<ul>
<li>hello (3)
<ul>
<li>hello (4)
<ul>
<li>hello (5)</li>
<li>hello (6)</li>
</ul>
</li>
<li>hello (7)</li>
</ul>
</li>
</ul>
</li>
<li>hello (2)
<ul>
<li>hello (8)</li>
</ul>
</li>
</ul>
答案 0 :(得分:3)
递归的工作方式正如您对Polymer所期望的那样。只需声明一个元素,然后在其模板中使用该元素:)
<script src='//www.polymer-project.org/components/platform/platform.js'></script>
<link rel='import' href='//www.polymer-project.org/components/polymer/polymer.html'>
<polymer-element name='tree-node' attributes='nodeData' noscript>
<template>
<ul>
<li>{{nodeData.title}} ({{nodeData.id}})</li>
<template repeat='{{child in nodeData.children}}'>
<tree-node nodeData='{{child}}'></tree-node>
</template>
</ul>
</template>
</polymer-element>
<script>
var data = [
{id: 1, title: 'hello', parent: 0, children: [
{id: 3, title: 'hello', parent: 1, children: [
{id: 4, title: 'hello', parent: 3, children: [
{id: 5, title: 'hello', parent: 4},
{id: 6, title: 'hello', parent: 4}
]},
{id: 7, title: 'hello', parent: 3}
]}
]},
{id: 2, title: 'hello', parent: 0, children: [
{id: 8, title: 'hello', parent: 2}
]}
];
data.forEach(function(nodeData) {
var treeNode = document.createElement('tree-node');
treeNode.nodeData = nodeData;
document.body.appendChild(treeNode);
});
</script>
答案 1 :(得分:0)
试试这个:
<polymer-element name="scary-cuisine" attributes="myArray">
<template>
<ul>
<template repeat="{{foo in myArray}}">
<li>{{foo.title}} {{foo.id}}
<ul>
<template repeat="{{bar in foo.children}}">
<li>{{bar.title}} {{bar.id}}
<ul>
<template repeat="{{foobar in bar.children}}">
<li>{{foobar.title}} {{foobar.id}}
<ul>
<template repeat="{{barfoo in foobar.children}}">
<li>{{barfoo.title}} {{barfoo.id}}</li>
</template>
</ul>
</li>
</template>
</ul>
</li>
</template>
</ul>
</li>
</template>
</ul>
<style>
:host {
font-family: sans-serif;
}
</style>
</template>
<script>
Polymer('scary-cuisine', {
created: function() {
this.myArray = [];
}
});
</script>
</polymer-element>
<scary-cuisine myArray="[{'id':'1', 'title':'hello', 'parent':'0', 'children':[{'id':'3', 'title':'hello', 'parent':'1', 'children': [{'id':'4', 'title':'hello', 'parent':'3', 'children':[{'id':'5', 'title':'hello', 'parent':'4'}, {'id':'6', 'title':'hello', 'parent':'4'}]}, {'id':'7', 'title':'hello', 'parent':'3'}]}]}, {'id':'2', 'title':'hello', 'parent':'0', 'children':[{'id':'8', 'title':'hello', 'parent':'2'}]}]"></scary-cuisine>