【问题标题】:Get the depth of an object or array获取对象或数组的深度
【发布时间】:2017-06-22 16:09:39
【问题描述】:

我得到类似这样的数据,并说我得到了无限组的深度。

data/group.data.json

module.exports = [
  {
    id: '1',
    title: 'Awesome Group',
    type: '1',
    groups: [
      {
        id: '5',
        title: 'Child in Level Two - A',
        type: '2',
        groups: [
          {
            id: '6',
            title: 'Child in Level Three - A',
            type: '2',
          },
          {
            id: '8',
            title: 'Child in Level Three - B',
            type: '2',
          }
        ]
      },
      {
        id: '7',
        title: 'Child in Level Two - B',
        type: '2',
      }
    ]
  },
  {
    id: '2',
    title: 'Rockers',
    type: '2',
  },
  {
    id: '3',
    title: 'Dazzlers',
    type: '3',
  }
];

我不能像下面这样手动执行此操作,如何动态迭代它直到结束?

<ul class="list-group list-group-flush">
  <template v-for="group in groupData">
    <a class="list-group-item" href="#">
      <h6>{{group.title}}</h6>
    </a>
    <template v-for="group in group.groups">
      <a class="list-group-item pl-40" href="#">
        <h6>{{group.title}}</h6>
      </a>
      <template v-for="group in group.groups">
        <a class="list-group-item pl-60" href="#">
          <h6>{{group.title}}</h6>
        </a>
      </template>
    </template>
  </template>
</ul>

<script>
  let groupData = require('../data/group.data');

  export default {
    data () {
      return {
        groupData,
      }
    }
  }
</script>

我想要一个答案,但不确定如何在我的情况下使用:https://stackoverflow.com/a/13523953/1292050

【问题讨论】:

标签: javascript vue.js vuejs2


【解决方案1】:

一种解决方案是简单地在其模板中引用组件本身。只要没有太多的元素,它应该是完全可以的。与此功能相关的唯一限制是为组件分配名称。当您全局注册组件时,这会自动完成。如果不这样做,只需在组件对象中指定一个属性名称即可。

请参阅the doc 以获得更完整的说明。

此外,您必须指定 a key 属性来循环模板中的组件。

最后,这是您的工作示例:

const tree = [{id:"1",title:"Awesome Group",type:"1",groups:[{id:"5",title:"Child in Level Two - A",type:"2",groups:[{id:"6",title:"Child in Level Three - A",type:"2"},{id:"8",title:"Child in Level Three - B",type:"2"}]},{id:"7",title:"Child in Level Two - B",type:"2"}]},{id:"2",title:"Rockers",type:"2"},{id:"3",title:"Dazzlers",type:"3"}];

Vue.component('Group', {
  name: 'Group',
  template: `<div>
    <a class="list-group-item" href="#">
      <h6>
        <template v-for="d in deep">-</template>
        {{ value.title }}
     </h6>
    </a>
    <group v-for="g in value.groups" 
      :value="g" 
      :deep="deep + 1" 
      :key="g.id">
    </group>
  </div>`,
  props: ['value', 'deep']
});

new Vue({
  el: '#app',
  data: {
    tree
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>

<div id="app">
  <group v-for="t in tree" 
    :value="t" 
    :deep="1" 
    :key="t.id">
  </group>
</div>

【讨论】:

    猜你喜欢
    • 2018-05-24
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 2020-08-07
    • 2013-12-19
    • 1970-01-01
    相关资源
    最近更新 更多