[英]How to render recursive components outside of parent component in Vue.js?
我有一个树数据结构,我需要递归地渲染它
const tree = [
{
name: 'hello',
children: [
{
name: 'world',
children: [
{
name: 'bye'
}
]
}
]
}
];
问题在于此组件应该像表行一样位于表内部,因此不能相互嵌套在DOM中
这看起来像是https://jsfiddle.net/zw4mydxb/2/
这就是我需要的结果
<tr>hello</tr>
<tr>world</tr>
<tr>bye</tr>
使用递归组件而不更改数据结构是否有可能实现?
您可以为此使用递归,以下代码段将为您提供帮助。
const tree = [ { name: "hello", children: [ { name: "world", children: [ { name: "bye" } ] }, { name: "hola" } ] }, { name: "how", children: [ { name: "is", children: [ { name: "life" } ] } ] } ]; function getData(tree) { if (tree && typeof tree[0].children === "undefined") return tree[0].name; var outputString = []; for (let i = 0; i < tree.length; i++) { if (typeof tree[i].children != "undefined") { outputString.push(tree[i].name, getData(tree[i].children)); } else { outputString.push(tree[i].name); } } return outputString.toString().split(","); } console.log(getData(tree));
现在您有了一个名称数组,可以迭代该数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.