Vue树形数据递归

父组件:

<template>
  <div class="home">
    <ul>
      <tree-item
      v-for="item in TreeData"
      :treeData="item"
      :key="item.name"
      >tree-item>
    ul>
  div>
template>
<script>
import TreeItem from '@/components/tree-item';
export default {
  data() {
    return {
      TreeData: [
        {
          name: "node-1",
          children: [
            {
              name: "node-1-1",
              children: [
                {
                  name: "node-1-1-1"
                },
                {
                  name: "node-1-1-2"
                },
                {
                  name: "node-1-1-3"
                }
              ]
            },
            {
              name: "node-1-2",
              children: [
                {
                  name: "node-1-2-1"
                },
                {
                  name: "node-1-2-2"
                },
                {
                  name: "node-1-2-3"
                }
              ]
            }
          ]
        },
        {
          name: "node-2"
        }
      ]
    }
  },
  components: {
    TreeItem
  }
}
script>

树形组件 子组件

<template>
  <li class="tree-item">
    <div class="name-text">{{ treeData.name }}div>

    <ul v-if="treeData.children && treeData.children.length" class="sub-items">
      <tree-item
      v-for="item in treeData.children"
      :treeData="item"
      :key="item.name"
      >tree-item>
    ul>
  li>
template>
<script>
export default {
  name: "tree-item", // 递归的关键
  props: {
    treeData: {
      type: Object,
      default() {
        return {}
      }
    }
  }
}
script>
<style lang="less" scoped>
  .tree-item {
    .name-text {
      text-align: left;
    }
  }
style>

你可能感兴趣的:(Vue)