I’m trying to build a custom HTML <input>
component for VueJS3. I’ve been following this tutorial:
https://dev.to/viniciuskneves/vue-custom-input-bk8
So far I managed to get the CustomInput.vue
component to work and emit the modified value back to the parent App.Vue.
<template> <label> {{ label }} <input type="text" :name="name" :value="value" @input="onInput" @change="onChange" /> </label> </template> <script> export default { name: 'CustomInput', props: { label: { type: String, required: true, }, value: { type: String, required: true, }, }, computed: { name() { return this.label.toLowerCase(); }, }, methods: { onInput(event) { this.$emit('input', event.target.value); }, onChange(event) { this.$emit('change', event.target.value); }, }, } </script>
What I don’t understand is – how will the emitted events be detected by the parent App.vue component? I can’t see it happens, and I can’t find it in the tutorial.
My App.Vue
looks like this:
<template> <custom-input :label="'Name'" :value="name"></custom-input> <div>{{ name }}</div> </template> <script> import customInput from "./components/CustomInput.vue"; export default { components: { customInput }, name: "App", data: function () { return { name: "", }; }, mounted() { this.name = "Thomas"; }, }; </script>
Thanks in advance for any help 🙂
Advertisement
Answer
This tutorial is for Vue 2 – for Vue 3 there is another tutorial (https://www.webmound.com/use-v-model-custom-components-vue-3/)
Emitting input
event works in Vue 2 only – for Vue 3 you will have to emit update:modelValue
and also use modelValue
as a prop instead of just value
.