首页 > 解决方案 > 如何在 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>

甚至可以在不改变数据结构的情况下使用递归组件来实现吗?

标签: javascriptvue.jsrecursionvue-component

解决方案


您可以为此使用递归,以下代码片段将为您提供帮助。

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));

现在你有一个名称数组,你可以迭代这个数组。


推荐阅读