【问题标题】:How do you create dynamic rowspan tables in vuejs?如何在 vuejs 中创建动态行跨度表?
【发布时间】:2020-05-30 19:53:21
【问题描述】:

如何使用 vueJs 将以下数据渲染到具有行跨度的 html 表格中?

数组

[
  {
    "id": 1,
    "name": "Dog",
    "param_id": 5,
    "total": "45.000"
  },
  {
    "id": 2,
    "name": "Cat",
    "param_id": 5,
    "total": "45.000"
  },
  {
    "id": 3,
    "name": "Fish",
    "param_id": null, 
    "total": "55.000"
  },
  {
    "id": 4,
    "name": "Bird",
    "param_id": 2, 
    "total": "75.000"
  }
]

这是一个结果示例

【问题讨论】:

    标签: javascript html laravel vue.js


    【解决方案1】:

    首先,您可以使用 Laravel Collection groupBy 方法按给定键 ('total') 对集合中的项目进行分组

    控制器代码

    //...
    
    $myElequentCollection = Model::where(...)->get();
    
    $grouped = $myElequentCollection->groupBy('total');
    
    $data = $grouped->toArray();
    
    //outpout
    /*
        [
            '45.000' => [
                ['id' => '1', 'name' => 'Dog', ...],
                ['id' => '2', 'name' => 'Cat', ...],
            ],
            '55.000' => [
                ['id' => '3', 'name' => 'Fish', ...],
            ],
            '75.000' => [
                ['id' => '4', 'name' => 'Bird', ...],
            ],
        ]
    */
    
    //...
    
    return view('viewName', compact('data'));
    

    HTML 代码示例

    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Total</th>
        </tr>
      </thead>
      <tbody>
        @foreach($data as $item)
        @foreach($item as $row)
        <tr>
          <td> {{ $row['id'] }}</td>
          <td> {{ $row['name'] }}</td>
          @if($loop->first )
          <td rowspan="{{ count($item) }}">{{ $row['total'] }}</td>
          @else
          <td>{{ $row['total'] }}</td>
          @endif
        </tr>
        @enforeach
        @endforeach
      </tbody>
    </table>
    

    【讨论】:

      猜你喜欢
      • 2020-05-14
      • 2021-11-02
      • 2021-07-23
      • 2018-04-07
      • 2012-10-18
      • 2020-05-08
      • 2020-05-06
      • 2016-09-08
      • 2021-07-30
      相关资源
      最近更新 更多