I am currently working on creating a custom Input component using Vue 3's composition API. However, I encountered an issue where updating the value with v-model resulted in receiving an empty string instead of the expected event value. Surprisingly, when I swapped out the custom Input
component with the default HTML input
, the value was updated as intended.
This is the code for the Input component:
<template>
<input
:type="type"
:id="name"
:name="name"
:placeholder="placeholder"
class="input"
v-model="modelValue"
/>
</template>
<script lang="ts">
import { computed } from 'vue';
export default {
name: 'Input',
props: {
modelValue: {
type: String,
required: true,
},
name: {
type: String,
required: true,
},
type: {
type: String,
default: 'text',
},
placeholder: {
type: String,
required: true,
},
},
setup(props: { value: string }, { emit }) {
const modelValue = computed({
get() {
return props.modelValue;
},
set(value) {
emit('input', value);
},
});
return { modelValue };
},
};
</script>
<form @submit.prevent="handleSubmit">
<Input :name="name" placeholder="Name*" v-model="name" />
<Button>Send</Button>
</form>
This is the setup method:
setup() {
const name = ref('');
function handleSubmit(data: Event) {
console.log(data, name.value);
}
watch(name, (old, newValue) => {
console.log(name, old, newValue);
});
return { name, handleSubmit };
},