首页 > 解决方案 > 如何使递归函数 vue.js 从孩子中获取数据

问题描述

我正在使用 vue.js 和 v-tree + vue2vis 网络,我有一棵树,里面有我所有的项目,比如这个:

items: [
          {
            id: 1,
            name: 'root',
            children: [
              {
                id: 2,
                name: 'child1',
                children: [
                  {
                    id: 3,
                    name: 'child3',
                  },
                  {
                    id: 4,
                    name: 'child34',
                  },
                ],
              },
              {
                id: 5,
                name: 'subroot',
                children: [
                  {
                    id: 6,
                    name: 'Mike',
                    children:[
                      {
                        id: 7,
                        name: 'Mini Mike',
                      }
                    ]
                  },
                  {
                    id: 8,
                    name: 'Hunt',
                  },
                ],
              },
              {
                id: 9,
                name: 'test',
                children: [
                  {
                    id: 10,
                    name: 'Brandon',
                  },
                  {
                    id: 11,
                    name: 'Sean',
                  },
                ],
              },
            ],
          },
        ],

我想要做的是,当我点击树中的一个项目时,它会为网络生成数据,如下所示:

nodes: [{'id':1 , label: 'root'},{'id':2 , label: 'child1'},{'id':3 , label: 'child3'}]
and so on for all the children and parents
same goes for the edage i want to create conection between parent and child
edage: [{'from': 1, 'to':2},{'from': 2, 'to':3}]

我为这个想法尝试了这个功能,但它不起作用

      makeNetConnection(items , itemKey) {
//items -> all the tree data
//itemKey-> its the item i click on the tree that i want to create the view
          for (let item of items) {
              if (item.name == itemKey) {
                this.nodes.push({'id':item.id , 'label':item.name});
                return item;
              }
              if (item.children) {
                  let i = this.makeNetConnection(item.children ,itemKey)
                  if (i) { 
                    this.nodes.push({'id':item.id , 'label':item.name});
                    this.edges.push({'from': item.id , 'to': i.id});
                    return i;
                  }
              }
          }

它复制了数组中的数据,而不是与我希望拥有的父级连接,[{'from': 1, 'to':2},{'from': 2, 'to':3},{'from': 2, 'to':4}] 并且所有项目的操作系统都打开

但是我有[{'from': 1, 'to':2},{'from': 1, 'to':3} , {'from': 1, 'to':2},{'from': 1, 'to':3}, {'from': 1, 'to':4}, {'from': 1, 'to':4}]

我不知道 middel 连接如何使其工作?

标签: javascripttypescriptvue.jsrecursionvuejs2

解决方案


Maybe overkill, but use traverse

const traverse = require('traverse');
const returnData=[];

traverse.forEach(function(item){
   returnData.push({id:item.id,label:item.value});
});

推荐阅读