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

14,792

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.

Share:
14,792
jeffcodes
Author by

jeffcodes

I spent 10 years in mental health and needed a change. Took some classes at the local CC and then a boot camp finishing in June 2017. Now I am doing web development! I have a passion for security and privacy, and hope to focus my career in that space long term.

Updated on June 05, 2022

Comments

  • jeffcodes
    jeffcodes almost 2 years

    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>