VueJS:使用v-for从嵌套对象列表中递归生成

时间:2019-10-09 18:26:54

标签: vue.js vuejs2

我希望Vue使用id item 1 A 1 B 1 C 2 D 2 E 2 F 递归生成数据结构,其中我的数据采用以下格式:

数据

id          item
1           A,B,C
2           D,E,F

v-for(如下)中的代码存在一些逻辑问题,因此没有输出。有人可以帮助我正确获取var myObj = { parent: { child1: { last_child1: { test: null } } } } 中的逻辑代码

以下是指向有效的codesandbox demo

的链接

这是我的组件层次结构:

NodeTree.vue

这是我的Vue SFC来源:

Tree.vue

NodeTree.vue

NodeTree.vue

<pre>

App.vue
  |
  |_Tree.vue
       |
       |_NodeTree.vue

</pre>

App.vue

<template>
  <div class="tree">
    <ul class="tree-list">
        <NodeTree :treeData="data" />
    </ul>
  </div>
</template>

<script>
import NodeTree from "./NodeTree";

export default {
  props: ["data"],
  components: {
    NodeTree
  }
};
</script>

<style>
.tree-list ul {
  padding-left: 16px;
  margin: 6px 0;
}
</style>

感谢您的帮助。

谢谢

1 个答案:

答案 0 :(得分:1)

确保您的数据是结构化的,以便您可以创建递归结构

App.vue:

<template>
  <div id="app">
    <tree :data="folder_Names" >
    </tree>
  </div>
</template>

<script>
import Tree from "./components/Tree";

export default {
  name: "App",
  data() {
    return {
      folder_Names: [
       { name: 'Parent1', children: [
         { name: 'Child1_1', children: [
           {name: 'Grandchild1_1_1'},
           {name: 'Grandchild1_1_2'} 
         ]},
        { name: 'Child1_2' } 
       ]},
       { name: 'Parent2', children: [
         { name: 'Child2_1', children: [
           {name: 'Grandchild2_1_1'},
           {name: 'Grandchild2_1_2'} 
         ]},
        { name: 'Child2_2' },
        { name: 'Child2_3' },
       ]}
    ]}
  },
  components: {
    Tree
  }
};
</script>

Tree.vue

<template>
  <div class="tree">
    <ul class="tree-list">
        <node-tree :treeData="data" />
    </ul>
  </div>
</template>

<script>
import NodeTree from "./NodeTree";

export default {
  props: ["data"],
  components: {
    NodeTree
  }
};
</script>

树节点

<template>
      <ul>
          <li :key="idx" v-for="(item,idx) in treeData">          
            {{ item.name }} 
            <my-node :treeData="item.children" />
          </li>
      </ul>  </template>

<script> 
   export default {   
      name: "MyNode",   
      props: ["treeData"],   
 </script>

https://codesandbox.io/s/vue-demo-recursive-fb-filemanager-folderlist-test-k9jo5