Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

求解:vue如何遍历数组对象中的数组。

要遍历的数据:
这只展示了第一层。
image.png

list: [
     {
         id: 1,
         name: "第一层",
         child: [],
     },
     {
         id: 1,
         name: "第一层",
         child: [
             {
                 id: 2,
                 name: "第一层第二层",
                 child: [],
             },
        ],
     },
     {
         id: 1,
         name: "第一层",
         child: [
             {
                 id: 2,
                 name: "第一层第二层",
                 child: [
                     {
                         id: 3,
                         name: "第一层第二层第三层",
                         child: [],
                     },
                 ],
             },
         ],
     },
 ],
 

foreach写的方法,
image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

递归组件上面都说了。各种组件库都有实现递归树组件的渲染的,通常直接用就好了。


另外一种方法是你可以把树结构压扁成列表结构,就可以v-for渲染出来的,相比递归组件要高效许多。
预览:
http://jsrun.net/ai2Kp/edit

function treeToList (tree) {
    const result = tree.map(i => (i.level = 0, i))
    for (let i = 0; i < result.length; i++) {
        if (!result[i].child) continue
        result[i].child.forEach(node => node.level = result[i].level + 1)
        result.splice(i + 1, 0, ...result[i].child)
    }
    return result
}

export default {
  data () {
    return {
      list: 'xxx'
    }
  },
  computed: {
    treeList () {
        return treeToList(this.list)
    }
  }
}

渲染:

<template>
    <div>
        <div
            v-for="node of treeList"
            :style="{
                paddingLeft: node.level * 20 + 'px'
            }"
            :key="node.id">
            {{ node.name }}
        </div>
    </div>
</template>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...