Rakesh K
Rakesh K

Reputation: 1320

Checkboxes not getting checked on load in Vue.js

I have a project using Vue.js and Laravel. I have some checkboxes to select instruments(music). Let me explain what i am trying to do- there is list of instruments with checkboxes... On load i need to show what instruments already user has selected those checkboxes should be checked.

so here is my code

 <div v-for="(instrument, index) in instruments">
  <input
    type="checkbox"
    :id="index"
    v-model="selectedInstruments"
    :value="instrument"
  />
  <label :for="index">{{ instrument.instrument }}</label>
</div>


  data() {
    return {
      instruments: [
        { id: 1, instrument: "guitar", created_at: null, updated_at: null },
        { id: 2, instrument: "drums", created_at: null, updated_at: null },
        { id: 3, instrument: "piano", created_at: null, updated_at: null }
      ],
      selectedInstruments: [
        { id: 2, instrument: "drums", created_at: null, updated_at: null }
      ]
    };
  }

Here everything is working fine but when the same data is coming from axios checkboxes are not checked. Here is the link for sandbox

Thanks in Advance.

UPDATED

here is axios code

        created(){
                getAllLists(){
            axios.get('/all-lists')
                 .then(response=>{
                  this.instruments = response.data;
                 })
          }

     this.selectedInstruments = this.currentList; 
          }

// this.currentList is a prop which is passed in blade file it is getting same structured data as above array from axios

Upvotes: 2

Views: 2370

Answers (1)

Roy J
Roy J

Reputation: 43881

You've made a brittle choice in modeling. The object in selectedInstruments is not actually one of the objects in instruments. If it looks exactly like one of them, Vue seems to be willing to call it a match. But if there's a mismatch in, say created_at, they are not the same and no box will be checked.

A better idea would be to use the id as the value:

 <input
    type="checkbox"
    :id="index"
    v-model="selectedInstruments"
    :value="instrument.id"
  />

then you just have an array of ids, which is less likely to mismatch strangely. You can make a computed to turn your array of ids into an array of items from instruments if you need to.

This ought to work as the computed:

selectedInstrumentObjects() {
  return this.selectedInstruments.map((id) => this.instruments.find((obj) => obj.id === id));
}

I've updated your sandbox to use it here.

Upvotes: 4

Related Questions