update b-form-checkbox in Vue

Viewed 1894

I have the following <b-form-checkbox> inside a <b-table>:

https://jsfiddle.net/fmattioni/L269rd7s/

Here is what I am trying to achieve:

1 - table starts with all checkboxes checked: this I can easily achieve through checked="true".

2 - as an example, try to uncheck a random box.

3 - now change the date from the calendar.

4 - here is where my issue starts: once the date is changed, I would like to return all the checkboxes to their initial states, which means that all of them should be checked.


I would like to achieve this through one of these two different ways:

  • option #1 - is there a way to include in my data items whether a column should be checked or not? This is what I tried to do in the following:

items: [
        {id: 1, check: true,},
        {id: 2, check: true,},
        {id: 3, check: true,},
      ]

but I can't find a way to tell <b-form-checkbox> to do that. As an example, I would like to have id: 2 initially set as check: false and the other as check: true. Is that possible?

  • option #2 - it would be also sufficient if I could somehow just reset all the values to tru once the date changes.

Any ideas?

2 Answers

Replace you #cell(check)="row" to #cell(check)="{ item }"

<div id="app">
  <div>
    <b-form-datepicker
    value='2021-04-25'
    >
    </b-form-datepicker>
    <b-table
    :items='items'
    >
      <template #cell(check)="{ item }">
        <b-form-checkbox
        v-model="item.check"                 
        >
        </b-form-checkbox>
      </template>
    </b-table>
  </div>
</div>

In that way the component receive your item from the table component. Your #cell slot is containing more data such index that neccessery for some else uses.

https://jsfiddle.net/eligiv/eumvgp4s/15/

I think there is no need to use watch because it's overhead; you can use @input to detect changes and call the reset method. I added a code snippet for better understanding.

new Vue({
  el: "#app",
  data() {
    return {
      date: new Date(),
      items: [{
          id: 1,
          check: true,
        },
        {
          id: 2,
          check: false,
        },
        {
          id: 3,
          check: true,
        },
      ]
    }
  },
  methods: {
    reset_checkboxes() {
      this.items.forEach((el) => {
        el.check = true
      })
    }
  }
});
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap@4.5.3/dist/css/bootstrap.min.css" />

<script src="https://unpkg.com/vue@2.6.12/dist/vue.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.min.js"></script>


<div id="app">
  <b-form-datepicker @input="reset_checkboxes" v-model='date'>
  </b-form-datepicker>
  <b-table :items='items'>
    <template #cell(check)="{ item }">
        <b-form-checkbox v-model="item.check" />
    </template>
  </b-table>
</div>

Related