Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap Vue, <b-table> with an checkbox input based on the bound item data for the table

I have a table that is filled with data. I have a selected property on the data I want to bind to the checkbox in the b-table. I can't seem to figure out how to do this.

My Data:

data: () => ({
  tableData: [
    {
      title: "title01",
      desc: "desc01",
      selected: false
    },
    {
      title: "title02",
      desc: "desc02",
      selected: false
    },
  ],
  tableColumns: [
    { key: "selected", label: "", sortable: false }
    { key: "title", label: "Title", sortable: false },
    { key: "desc", label: "Description", sortable: false }
})

The html:

<b-table id="myTabel"
  hover
  striped
  :items="tableData"
  :fields="tableColumns">
  <template slot="selected" slot-scope="row">
    <b-form-group>
      <input type="checkbox" v-model="How_To_Bind_To_Object_Prop?">
    </b-form-group>
  </template>
</b-table>

For the life of me I can't get the v-model set up to actually bind to the table data. v-model="tableData.selected" bind all check boxes to all data objects. So, if you check one, you check all and vise versa. I just can't figure out how to bind it to that row's data only.

I can do this by using more traditional HTML and using Vue's v-for to loop through the tableData to bind each table row. However, we're trying to move most, if not all, of our forms to using bootstrap-vue.

So, this works beautifully:

<table>
    <thead>
        <tr>
            <th :key="key" v-for="(tableColumn, key) in tableColumns">
                {{ tableColumn.label }}
            </th>
        </tr>
    </thead>
    <tbody>
        <tr :key="key" v-for="(tableRow, key) in tableData">
            <td>
                <input type="checkbox" 
                    v-model="tableRow.selected">
            </td>
            <td>
                {{ tableRow.title }}
            </td>
            <td>
                {{ tableRow.desc }}
            </td>
        </tr>
    </tbody>
</table>
like image 707
jeffcodes Avatar asked Jan 02 '23 07:01

jeffcodes


1 Answers

You could access the row item as follows inside the scoped slot and bind the nested checkbox to the selected property:

<template v-slot:cell(selected)="row">
   <b-form-group>
       <input type="checkbox" v-model="row.item.selected" />
   </b-form-group>
</template>

For more info, see the Table - Custom rendering documentation.

like image 130
Boussadjra Brahim Avatar answered Jan 13 '23 11:01

Boussadjra Brahim