I'm new with Typescript and I'm trying use defineEmits to send chosen radio to the parent component. I success with input field, send data to parent, but with radio is something different.
I declare array of radio in parent component with name and description, send to the child component and in child component I have button which for every click I change radio. The plan chosen radio use in parent component.
Parent Component
<script lang="ts">
import { useField, useForm } from 'vee-validate'
import { string } from 'yup'
export default defineComponent({
components: {},
})
</script>
<script lang="ts" setup>
const subtitle: string | number = 'Lorem ipsum dolor sit amet consectetur.'
const { handleSubmit, errors } = useForm({
validationSchema: {
checked: string().required('enter the field.'),
},
initialValues: {
checked: ''
},
})
const { value: checked } = useField<string>('checked')
const arrayRadio: { name: string; description: string }[] = [
{
name: 'First',
description: 'Lorem ipsum dolor sit amet consectetur.',
},
{
name: 'Second',
description: 'Lorem ipsum dolor sit amet consectetur.',
},
]
</script>
<template>
<main class="min-h-screen">
<div class="base-container">Content</div>
<InputRadio v-model="checked" :array-radio="arrayRadio" />
</main>
</template>
Child Component
<script lang="ts" setup>
import { ref } from 'vue'
interface Props {
subtitle?: string
arrayRadio?: any
}
const props = withDefaults(defineProps<Props>(), {
subtitle: '',
arrayRadio: '',
})
const emit = defineEmits<{
(event: 'update:arrayRadio', value: any): void
}>()
const { arrayRadio, subtitle } = toRefs(props)
const selected = ref(props.arrayRadio[1])
function updateInput(event: Event) {
emit('update:arrayRadio', event.target.value)
}
</script>
<template>
<div>
<div v-for="plan in arrayRadio" :key="plan.name"
class="mx-auto w-full max-w-md">
<input id="html" v-model="selected" type="radio" :value="plan.name" @click="updateInput">
<label for="html">{{ plan.name }}</label><br>
</div>
</div>
</template>