search

Home  >  Q&A  >  body text

Correct way to make Vue custom checkbox component

<p>How to create a custom checkbox in Vue. When the checkbox changes, it should call the function. I got the error "Cannot read property 'id' of undefined" and warning "An unhandled error occurred during execution of a native event handler"</p> <p>Custom checkbox:</p> <pre class="brush:js;toolbar:false;"><template> <div class="filter"> <input :ref="id" :id="id" type="checkbox" class="filter-checkbox" @change="$emit('do', $emit)" /> <span>{{ label }}</span> </div> </template> <script> export default { name: "Checkbox", props: { label: { type: String }, isSelected: { type: Boolean }, id: { type: String } }, } </script></pre> <p>I want to use this in a parent component: </p> <p> <pre class="brush:js;toolbar:false;"><Checkbox v-for="filter of filters" :key="filter.id" :label="filter.name" :id="filter.id" v-model="filter.selected" @do="mutuallyExclusive(filter.id)" /></pre> </p>
P粉135292805P粉135292805443 days ago507

reply all(1)I'll reply

  • P粉343408929

    P粉3434089292023-09-03 00:21:00

    Undefined and unhandled errors cannot be repeated and you need to debug further.

    But you are emitting the emit function, which is strange, and the value is always filter.id whether checked or not.

    You may want to do something like the following:

    new Vue({
      el: '#app',
      components: {
        'Checkbox': {
          template: '#checkbox-template',
          props: {
            label: {
              type: String,
              default: ''
            },
            value: {
              type: Boolean,
              default: false
            },
            id: {
              type: String,
              default: ''
            }
          }
        }
      },
      data: () => ({
        filters: [{
          id: 1,
          name: 'a',
          selected: true,
        },{
          id: 2,
          name: 'b',
          selected: false,
        }]
      }),
      methods: {
        mutuallyExclusive(value) {
          console.log(value)
        }
      }
    })
    <div id="app">
      <Checkbox 
        v-for="filter of filters" 
        :key="filter.id" 
        :label="filter.name" 
        :id="filter.id" 
        v-model="filter.selected" 
        @change="mutuallyExclusive" 
      />
    </div>
    
    <template id="checkbox-template">
      <div class="filter">
        <input 
          :ref="id" 
          :id="id" 
          type="checkbox" 
          class="filter-checkbox"
          :checked="value"
          @change="$emit('change', {value:$event.target.checked, id})" 
        />
        <span v-if="label">{{ label }}</span>
      </div>
    </template>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.14/vue.min.js"></script>

    reply
    0
  • Cancelreply