如何发射选定的无线电到父组件?



我是Typescript的新手,我正在尝试使用defineemit将选择的无线电发送到父组件。如果输入字段成功,则将数据发送给父节点,但使用无线电则不同。

我在父组件中声明了一个带有名称和描述的无线电数组,发送给子组件,在子组件中我有一个按钮,每次点击我都会改变无线电。

选择在父组件中使用的计划。父组件

<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>

子组件

<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>

您正在发出'update:arrayRadio'事件并监听array-radio

我们可以理解你从camelCase到kebabl -case发出的事件,但这里的问题是updatearrayRadio之前。

尝试重命名它,像这样:

function updateInput(event: Event) {
emit('arrayRadio', event.target.value)
}
const emit = defineEmits<{
(event: 'arrayRadio', value: any): void
}>()

你甚至可以在名称上使用更新,但是你必须在组件之间使用相同的值。

最新更新