如何创建表,表头在左侧,其中有多行

时间:2018-09-30 10:56:13

标签: css vue.js twitter-bootstrap-3

我有一个表,其中可能有各种列(标题)以及其中各种数据。正在使用v-for填充它。示例代码如下:

     <div class="table-responsive">
        <table class="table">
            <thead><tr>
                <th v-for="header in table_headers">
                    <span>@{{header}}</span>
                </th>
            </tr></thead>
            <tbody>
                <tr v-for="body in table_body">
                    <td>
                       @{{body}}    
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

哪个表创建如下:

+-------------+---------+---------+
|    Name     | Middle  | Surname |
+-------------+---------+---------+
| Christopher | Ashton  | Kutcher |
| William     | Bradley | Pitt    |
| Thomas      | Sean    | Connery |
+-------------+---------+---------+

如何将其转换为表,该表在第一列中包含标题,在第二列中包含所有数据:

+---------+-------------+
| Name    | Christopher |
| Middle  | Ashton      |
| Surname | Kutcher     |
| ------- | ----------- |
| Name    | William     |
| Middle  | Bradley     |
| Surname | Pitt        |
| ------  | ----------- |
| Name    | Thomas      |
| Middle  | Sean        |
| Surname | Connery     |
+---------+-------------+

JSON中的数据:

{
  "columns": {
    "0": "Name",
    "1": "Middle",
    "2": "Surname"
  }
}

{
  "data": {
    "Name": ["Christopher", "William", "Thomas"],
    "Middle": ["Ashton", "Bradley", "Sean"],
    "Surname": ["Kutcher", "Pitt", "Connery"]
  }
}

1 个答案:

答案 0 :(得分:2)

假设您具有以下数据:

data() { return {
  names: [ 
    { "Name": "Christopher", "Middle": "Ashton", "Surname": "Kutcher" },
    { "Name": "William", "Middle": "Bradley", "Surname": "Pitt" },
    { "Name": "Thomas", "Middle": "Sean", "Surname": "Connery" },
  ]
}

这将是您的HTML:

<table>
  <tr v-for="name in names">
    <td>
      <div v-for="key in Object.keys(name)">{{ key }}</div>
    </td>
    <td>
      <div v-for="value in Object.values(name)">{{ value }}</div>
    </td>
  </tr>
</table>

let template = `<table>
  <tr v-for="name in names">
    <td>
      <div v-for="key in Object.keys(name)">{{ key }}</div>
    </td>
    <td>
      <div v-for="value in Object.values(name)">{{ value }}</div>
    </td>
  </tr>
</table>`

new Vue({
  el: "#app",
  template,
  data() { return {
      names: [ 
        { "Name": "Christopher", "Middle": "Ashton", "Surname": "Kutcher" },
        { "Name": "William", "Middle": "Bradley", "Surname": "Pitt" },
        { "Name": "Thomas", "Middle": "Sean", "Surname": "Connery" },
      ]
    }
  }
});
<script src="https://vuejs.org/js/vue.min.js"></script>

<div id="app"></div>