在表行中列出分组数据

时间:2017-11-30 20:44:52

标签: vue.js vue-component

我假设我有以下数据

data() {
    return {
        users: [
            {country: 'USA', name: 'Taylor'},
            {country: 'UK', name: 'Tony'},
            {country: 'USA', name: 'Mary'},
            {country: 'JAPAN', name: 'Jane'},
            {country: 'JAPAN', name: 'Moses'},
            // More users from different countries in the world
        ]
    }
}

我想按国家/地区分组,我的最终表结构是这样的,按国家名称desc排序。

<table>
    <tr>
        <th>Country</th>
        <th>User</th>
    </tr>
    <tr>
        <td colspan="2">USA</td>
    </tr>
    <tr>
        <td></td>
        <td>Taylor</td>
    </tr>
    <tr>
        <td></td>
        <td>Mary</td>
    </tr>
    <tr>
        <td colspan="2">UK</td>
    </tr>
    <tr>
        <td></td>
        <td>Tony</td>
    </tr>
    <tr>
        <td colspan="2">JAPAN</td>
    </tr>
    <tr>
        <td></td>
        <td>Jane</td>
    </tr>
    <tr>
        <td></td>
        <td>Moses</td>
    </tr>


</table>

我怎样才能做到这一点?我试过和Lodash的小组一起玩,但是无法实现它

let users = _.groupBy(this.users, function(user) { return user.country })

1 个答案:

答案 0 :(得分:8)

以下是如何在没有任何库的情况下执行此操作的一个示例。

console.clear()

new Vue({
  el: "#app",
  data:{
    users: [
      {country: 'USA', name: 'Taylor'},
      {country: 'UK', name: 'Tony'},
      {country: 'USA', name: 'Mary'},
      {country: 'JAPAN', name: 'Jane'},
      {country: 'JAPAN', name: 'Moses'},
      // More users from different countries in the world
    ]
  },
  computed:{
    byCountry(){
      return this.users.reduce((acc, user) => {
        (acc[user.country] = acc[user.country] || []).push(user.name)
        return acc
      }, {})
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<div id="app">
  <table>
    <tr>
        <th>Country</th>
        <th>User</th>
    </tr>
    <template v-for="people, country in byCountry">
      <tr>
        <td colspan="2">{{country}}</td>
      </tr>
      <tr v-for="person in people">
        <td></td>
        <td>{{person}}</td>
      </tr>
    </template>    
  </table>
</div>