Search code examples
vue.jsvuetify.jsv-data-table

Using v-slot:body with v-checkbox row selector


When using v-slot:body with a v-checkbox for the row selection I am getting an unexpected behavior compared to a v-data-table without any v-slot:body. When the "items" object changes all the checkboxes are "selected" in the v-slot:body.

What is different from my v-checkbox and the one used by the v-data-table without v-slot:body? Is there a way to fix this while still using the body slot?

<v-data-table
  v-model="selected"
  :headers="headers"
  :items="desserts"
  item-key="name"
  show-select
  dense
  hide-default-footer
  class="elevation-1"
>
  <template v-slot:body="{ items }">
    <tbody>
      <tr v-for="d in items" :key="d.name">
        <td>
          <v-checkbox
            v-model="selected"
            :value="d"
            style="margin:0px;padding:0px"
            hide-details>
          </v-checkbox>
        </td>
        <td>{{ d.name }}</td>
        <td>{{ d.calories }}</td>
      </tr>
    </tbody>
  </template>
</v-data-table>

Reproduction: https://codepen.io/Straktor/pen/gOGpoqJ


Solution

  • First grab the isSelected and select functions from the body slot.

    <template v-slot:body="{ items, isSelected, select}">
    

    If you check vuetify's v-data-table API slots section, you can notice that the body slot includes the isSelected and select methods. https://vuetifyjs.com/en/api/v-data-table/#slots

    body slot preview

    Instead of individual item slot. In body's slot you need to pass the item to these functions. So, in order to work with your v-checkbox. Configure them this way. We start removing the v-model value you used since that is managed by the data table. Then we pass our item d the one you defined in your v-for to the selection functions.

    <v-checkbox
       :input-value="isSelected(d)"
       style="margin:0px;padding:0px"
       color="#535353"
       hide-details
       @click="select(d,!isSelected(d))"
    >                   
    </v-checkbox>
    

    Here's your example codepen working properly: https://codepen.io/cmfc31/pen/VwMvYpy?editors=1010