簡體   English   中英

如何在Vue.js的父組件之外呈現遞歸組件?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM