javascript - 如何在 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));
现在你有一个名称数组,你可以迭代这个数组。
推荐阅读
- vue.js - Vee 验证 - 重复表单 - 复选框
- python - 行之间的熊猫日期时间增量按另一列分组
- javascript - 使用 for/in 创建的 JS 对象多次将同一个对象返回到数组
- c++ - 检查登录,C++
- payment - 使用 QBXML 如何从远程系统的 ReceivePayment 中取消交易?
- meta-tags - 我的 React-Helmet 在我的登录组件中不起作用?
- html - 在R中将字体系列更改为可格式化
- c++ - 项目构建中的构建错误具有 INET 参考
- java - Spring REQUIRES_NEW 内部事务没有被持久化
- javascript - Javascript filter function is returning the removed element and not the new array