如何在没有_rowVariant的情况下动态更改表格行的颜色?

Mat*_*zer 2 html javascript vue.js bootstrap-4 bootstrap-vue

我正在使用 bootstrap-vue 表来显示我从 JSON 中检索的信息。我收到的一个信息是一个名为“Status”的 int,我想根据此变量更改整行的颜色,例如,如果 Status 等于 1,则行为绿色。]

在bootstrap-vue的文档中,它显示了根据项目数组数据中每个元素内的 _rowVariant 对象更改颜色的行,但是如何在我的项目数组中没有此对象的情况下更改行的颜色?如果不可能,如何将此变量插入数组的每个对象中?

这是有关表格内容的代码:

<b-container fluid>
  <b-table hover :items="requests" :fields="fields"
  @row-clicked="onRowClicked"
  >

  <template slot="show_details" slot-scope="row">
  <!-- we use @click.stop here to prevent emitting of a 'row-clicked' event  -->
  <b-button size="sm" @click.stop="row.toggleDetails" class="mr-2">
   {{ row.detailsShowing ? 'Hide' : 'Show'}} Details
  </b-button>
  </template>
  <template slot="row-details" slot-scope="row">
    <b-card>
      <b-row class="mb-2">
        <b-col sm="3" class="text-sm-right"><b>Info 1:</b></b-col>
        <b-col>{{ row.item.horas_info }}</b-col>
      </b-row>
      <b-row class="mb-2">
        <b-col sm="3" class="text-sm-right"><b>Info 2:</b></b-col>
        <b-col>{{ row.item.pdf }}</b-col>
      </b-row>
      <b-button size="sm" @click="row.toggleDetails">Hide Details</b-button>
    </b-card>
  </template>
  </b-table>
</b-container>
Run Code Online (Sandbox Code Playgroud)

itt*_*tus 6

您可以使用计算属性向项目列表添加额外的字段:

computed: {
  formartedItems () {
    if (!this.requests) return []
    return this.requests.map(item => {
      item._rowVariant  = this.getVariant(item.Status)
      return item
    })
  }
},
methods: {
  getVariant (status) {
    switch (status) {
      case 1:
        return 'success'
      case 1:
        return 'danger'
      default:
        return 'active'
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在 HTML 代码中:

<b-table hover :items="formartedItems" :fields="fields" @row-clicked="onRowClicked">
...
</b-table>
Run Code Online (Sandbox Code Playgroud)

如果你想要更多的自定义样式,你可以检查tdClassthClass或者thStyle在 bootstrap-vue 表中。


小智 5

添加:tbody-tr-class="rowClass"标签<b-table :tbody-tr-class="rowClass"></table>并添加rowClass到方法中:

methods: {
  rowClass(item, type) {
    if (!item || type !== 'row') return
    if (item.user_id == this.$auth.user.id) return 'table-success'
  }
}
Run Code Online (Sandbox Code Playgroud)