【发布时间】:2017-07-18 01:00:16
【问题描述】:
我尝试使用组件在 Vue 中构建数据树。
考虑以下数据:
"data": [
{
"id": 1,
"name": "foo",
"children": [
{
"id": 2,
"name": "bar",
"children": []
},
{
"id": 3,
"name": "hulu",
"children": []
}
]
},
{
"id": 4,
"name": "foobar",
"children": [
{
"id": 5,
"name": "foobar hulu",
"children": []
}
]
}]
现在我想用如下表格输出它:
ID ║ 名称 ║ 路径
1 ║ 富 ║ /富
2 ║ 酒吧 ║ /foo/bar
3 ║ 葫芦 ║ /foo/hulu
4 ║ foobar ║ /foobar
5 ║ foobar 葫芦 ║ /foobar/foobar 葫芦
如果有可用的子级,我尝试使用“调用”自身的组件。问题是 Vue.js 只允许一个根元素。
我的组件:
var Element = {
props: ['context', 'path'],
name: 'self',
template: `
<tr>
<td>{{context.id}}</td>
<td>{{context.name}}</td>
<td>{{path}}</td>
</tr>
<self v-if="context.children.length != 0" v-for="child in context.children" :context="child" :path="path + '/' + child.name"></self>
`
};
var Tree = {
components: {
'element': Element
},
template: `
<table v-if="elements.length != 0">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Path</th>
</tr>
</thead>
<element v-for="element in elements" :context="element" :path="'/' + element.name"></element>
</table>
`,
你会如何绕过这个问题?我尝试将元素模板包装在 tbody 中。这将正确计算路径并输出所有元素,但是这会产生嵌套在列中的行并且看起来非常难看。
有什么想法吗?
【问题讨论】:
标签: javascript html vue.js vuejs2