0

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!

4
  • I think the best way is to copy your prop into a data variable. Use this data variable a v-model on your input field. This will rerender on this v-model Commented Nov 16, 2022 at 8:03
  • @Wimanicesir can you elaborate a bit more please? I got this error when I tried to save the prop in a variable: Getting a value from the props in root scope of <script setup> will cause the value to lose reactivity Commented Nov 16, 2022 at 11:28
  • I think you didn't define your data correctly. I would advise to take a look at this: stackoverflow.com/questions/40408096/… Commented Nov 16, 2022 at 12:41
  • @Wimanicesir thanks but still doesn't work for me. I added the following inside InputComponent and referenced data in the input's :value attribute let data = ref(''); onMounted(() => { data.value = props.text; }); No input/text shows in the field. Commented Nov 16, 2022 at 13:08

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.