mardi 1 octobre 2019

Binding with v-model in custom checkbox component doesn't work

I'm trying to build a custom checkbox component with options that are generated with a v-for loop from an array with options and values. How can I bind the v-model correctly to the checkbox component so that it's correctly updated?

The problem now is that the model only updates to the latest checkbox that is checked and does not give an array with all checked options.

Vue.component('ui-checkbox', {
         props: {   
    label: {
      type: String,
      required: true,
    },
    index: {
      type: Number
    },
    inputValue: {
      type: String
    }
  },
  methods: {
    onChange(e) {
      this.$emit('input', e.target.value);
    },
  },
        template: `<div>
    <input 
      :id="index"
      type="checkbox"
      :value="inputValue"
      @change="onChange" />
    <label :for="index">
      
    </label>
  </div>`,
})

new Vue({
  el: "#app",
  data: {
    checkOptions: [
      {
        label: 'Option 1',
        value: 'value of option 1',
      },
      {
        label: 'Option 2',
        value: 'value of option 2',
      },
      {
        label: 'Option 3',
        value: 'value of option 3',
      },
      {
        label: 'Option 4',
        value: 'value of option 4',
      },
    ],
    myCheckBoxModel: []
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
   <span>checked Checkboxes:  </span>
   <ui-checkbox
     v-for="(option, index) in checkOptions"
     v-model="myCheckBoxModel"
     :key="index"
     :index="index"
     :input-value="option.value"
     :label="option.label" />    
</div>



Aucun commentaire:

Enregistrer un commentaire