2017-06-22 113 views
0

我得到的數據是這樣的,並說我得到了組的深度無窮大。獲取對象或數組的深度

數據/ 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

+1

我認爲這是不太實際使用n維數組,其中N> 3。你應該嘗試重構你的數據 –

+1

你應該看看如何編寫遞歸組件:https://vuejs.org/v2/examples/tree-view.html – Elfayer

回答

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>