Correct way to make Vue custom checkbox component
P粉135292805
2023-09-02 18:22:50
<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>
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: