I'm having trouble to figure out how to update an input element's value from the parent accurately. Below I have a simplified code to explain my problem more clearly. Hope someone can give me a hand to solve this in a correct way!
ParentComponent:
<script setup>
const form = useForm({
payment_number: '',
});
const cardNumberChecker = value => {
const cleaned = value.toString().replace(/\D/g, '');
const trimmed = cleaned.slice(0, 16);
const grouped = trimmed ? trimmed.match(/.{1,4}/g).join(' ') : '';
updateCardNumber.value++; // Current fix
form.payment_number = grouped;
};
<script>
<template>
<InputComponent
:update="updateCardNumber" // Current fix
:text="form.payment_number"
@input-trigger="cardNumberChecker"
></InputComponent>
</template>
InputComponent:
<script setup>
const props = defineProps({
update: { type: Number, default: 0 }, // Current fix
text: { type: String, default: '' },
});
defineEmits(['input-trigger']);
</script>
<template>
<input
:value="text"=
type="text"
@input="$emit('input-trigger', $event.target.value)"
/>
</template>
On input event, cardNumberChecker
is filtering and cleaning the input value. The issue is when a character inserted is not allowed, thus not changing form.payment_number
variable and hence not updating the InputComponent causing to allow the keyboard inputted character to show in the input field anyway.
As a temporary fix I have added a counter that increments on each keyboard input to cause the InputComponent to rerender.
Is there a proper Vue way to sort this out? Thank you!