1👍
You can use v-model to bind a parent ref to the child. The child accepts the v-model as a prop, and emits the value back to the parent whenever it changes.
Parent.vue
<template>
<child v-model="phone" />
</template>
<script setup>
import child from './child.vue'
import { ref } from 'vue'
const phone = ref('test')
</script>
Child.vue
<template>
<UContainer class="mt-4">
<UInput
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
class="text-left"
:placeholder="$t('registration.cellphone')"
icon="i-heroicons-phone"
type="phone"
name="phone"
/>
</UContainer>
</template>
<script setup>
defineProps(['modelValue']);
defineEmits(['update:modelValue']);
</script>
0👍
you can use the ref attribute in the child component and the onUpdated lifecycle hook in the parent component.
Child Component
<template>
<input
v-model="phoneValue"
:placeholder="placeholder"
:type="type"
:name="name"
/>
</template>
<script setup>
import { ref, defineProps } from 'vue';
const { modelValue, placeholder, type, name } = defineProps(['modelValue', 'placeholder', 'type', 'name']);
const phoneValue = ref(modelValue);
// Emit the updated value when the phoneValue changes
watch(phoneValue, (newValue) => {
emit('update:modelValue', newValue);
});
</script>
Parent Component:
<template>
<div>
<label for="phone" class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300">{{
$t('nav.cellphone')
}}</label>
<div class="relative mb-6" dir="ltr">
<UInput
v-model="phone"
class="text-left"
:placeholder="$t('registration.cellphone')"
icon="i-heroicons-phone"
type="phone"
name="phone"
/>
</div>
</div>
</template>
<script setup>
import { ref, watch } from 'vue';
import UInput from './UInput.vue'; // Import the child component
const phone = ref('');
// Watch for changes in the phone value and do something with it
watch(phone, (newValue) => {
// Handle the updated value here (e.g., send it to an API, perform validation, etc.)
console.log('New Phone Value:', newValue);
});
</script>
use the ref function to create a reference for the phone value in the parent component. The watch function is used to observe changes to the phone value
- [Vuejs]-Vue 2 – Create form with abstract v-model property
- [Vuejs]-Vue.js / import export ES6 issue with const
Source:stackexchange.com