2017-10-06 124 views
1

我正在重寫一些較舊的代碼,並使用Vue作爲替換。除了更改一個使用車把模板的表格之外,這一切都很順利。Vue:在表格中顯示嵌套數據

使用嵌套的句柄{{each}}我可以在表格行中顯示相關數據的同時查看嵌套的數據結構:例如,使用把手:https://jsfiddle.net/6dsruo40/1/

我無法弄清楚如何使用Vue公司與v-for

撥弄一樣做玉米粥,因爲我有:https://jsfiddle.net/cj7go6bv/

我不知道如何通過工作數據結構的同時保持<tr>就像在車把

這是我使用的數據結構,但它是靈活:

var data = [ 
    { 
key: "Region 1", 
values: [ 
    { 
    key: "Sub region 1", 
    values: [ 
     { 
     site: "Site A", 
     timestamp: 1507246300935, 
     total: 3, 
     }, 
     { 
     site: "Site B", 
     timestamp: 1507246300818, 
     total: 0, 
     }, 
     { 
     site: "Site C", 
     timestamp: 1507246300936, 
     total: 0, 
     } 
    ], 
    }, 
    { 
    key: "Sub region 2", 
    values: [ 
     { 
     site: "Site A", 
     timestamp: 1507246301442, 
     total: 20, 
     }, 
     { 
     site: "Site B", 
     timestamp: 1507246301788, 
     total: 5, 
     } 
    ] 
    }, 
    { 
    key: "Sub region 3", 
    values: [ 
     { 
     site: "Site A", 
     timestamp: 1507246302503, 
     total: 66, 
     }, 
     { 
     site: "Site B", 
     timestamp: 1507246302783, 
     total: 2 
     } 
    ] 
    } 
] 
    }, 
    { 
key: "Region 2", 
values: [ 
    { 
    key: "Sub region 1", 
    values: [ 
     { 
     site: "Site A", 
     timestamp: 1507246306789, 
     total: 0, 
     }, 
     { 
     site: "Site B", 
     timestamp: 1507246307439, 
     total: 6, 
     } 
    ] 
    }, 
    { 
    key: "Sub region 2", 
    values: [ 
     { 
     site: "Site A", 
     timestamp: 1507246308269, 
     total: 10, 
     }, 
     { 
     site: "Site B", 
     timestamp: 1507246308683, 
     total: 30, 
     } 
    ] 
    } 
] 
} 
]; 

的Vue公司的代碼,我很謙虛到目前爲止

Vue.component('project-table', { 
    template: '#table-template', 
    props: { 
    data: Array 
    } 
}); 

var app = new Vue({ 
    el: '#table-container', 
    data: {data: sites}, 
    }); 

而且模板:

<div id="table-container"> 
    <project-table :data="data"></project-table> 
</div> 
    <script id="table-template" type="text/x-template"> 
     <table class="u-full-width"> 
      <thead> 
       <tr> 
       <th>Project location</th> 
       <th>Total</th> 
       <th>Timestamp</th> 
      </tr> 
     </thead> 
     <tbody> 
     <tr class="name-row" v-for="item in data"> 
      <th class="name" colspan="3">{{item.key}}</th> 
     </tr> 
     <tbody> 
    </table> 
</script> 

在Vue公司的機制,就像是把手進行顯示的表是什麼?謝謝!

回答

1

以下是更新模板的相關部分。

<tbody> 
    <template v-for="item in data"> 
    <tr class="name-row" > 
     <th class="name" colspan="3">{{item.key}}</th> 
    </tr> 
    <template v-for="subregion in item.values"> 
     <tr> 
     <th class="group-name" colspan="4">{{subregion.key}}</th> 
     </tr> 
     <tr v-for="site in subregion.values"> 
     <td>{{site.site}}</td> 
     <td>{{site.total}}</td> 
     <td> 
      <span>{{site.timestamp}}</span> 
     </td> 
     </tr> 
    </template> 
    </template> 
<tbody> 

並更新了fiddle

重點是利用template元素每次迭代渲染多個tr

+0

這太棒了@bert!很簡單。 '