Looking to develop a customized checkbox component using Vue.js 2.6 that remains stateless, receiving its value as a prop and emitting an event to the parent component upon user input without storing any data internally.
Here is the simplified single-file component:
<script lang="ts">
import Vue from 'vue';
export default Vue.extend({
functional: true,
props: {
value: {
type: Boolean,
default: false,
},
},
});
</script>
<template functional lang="pug">
label
input(type="checkbox" :checked="value" ref="input"
@input="(listeners['input'] || (() => {}))($event.target.checked)")
</template>
This generates the following render function:
var render = function(_h, _vm) {
var _c = _vm._c
return _c("label", [
_c("input", {
ref: "input",
attrs: { type: "checkbox" },
domProps: { checked: _vm.value },
on: {
input: (_vm.listeners["input"] || function() {})(
_vm.$event.target.checked // Issue occurs here
)
}
})
])
}
var staticRenderFns = []
render._withStripped = true
Parent component:
<template lang="pug">
form
checkbox(:value="value" @input="value = $event")
</template>
<script lang="ts">
import Vue from 'vue';
import { default as Checkbox } from './checkbox.vue';
export default Vue.extend({
components: {
checkbox: Checkbox,
},
data() {
return { value: false };
},
});
</script>
When dealing with the native input element to trigger the input
event, I aim to pass the checked
property of the input to the parent listener (if it exists).
I've attempted using $event.target.checked
and $refs.input.checked
in the event handler for this purpose but faced limitations due to not having direct access within a functional template:
TypeError: "_vm.$refs is undefined"
Is there a workaround to access the native HTML element triggering an event within the attached event handler of a functional component template? Alternatively, should I resort to utilizing a stateful component in such cases?