gpt4 book ai didi

javascript - 正确输出嵌套数组

转载 作者:太空宇宙 更新时间:2023-11-04 15:58:30 24 4
gpt4 key购买 nike

我尝试使用组件在 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 ║ foo ║/foo
2 ║ 酒吧 ║/foo/bar
3 ║ 葫芦 ║/foo/hulu
4 ║ foobar ║/foobar
5 ║ foobar hulu ║/foobar/foobar hulu

我尝试使用一个组件,如果有可用的子组件,它会“调用”自身。问题是 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 内。这将正确计算路径并输出所有元素,但是这会产生嵌套在列内的行,看起来非常难看。

enter image description here

有什么想法吗?

最佳答案

展平路径。

Vue.component("flat-tree",{
props:["paths"],
template: "#flat-tree-template",
methods:{
flatten(data, root, accumulator){
return data.reduce((acc, val) => {
accumulator.push({
id: val.id,
name: val.name,
path: root + val.name
});
if (val.children)
return this.flatten(val.children, root + val.name + "/", accumulator);
else
return accumulator;
}, accumulator);
}
},
computed:{
flattened(){
return this.flatten(this.paths, "/", []);
}
}
})

模板

<template id="flat-tree-template">
<table>
<tr v-for="path in flattened">
<td>{{path.id}}</td>
<td>{{path.name}}</td>
<td>{{path.path}}</td>
</tr>
</table>
</template>

Working example .

关于javascript - 正确输出嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42485335/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com