Vue3 script setup自定义输入组件v-model绑定缺required prop及类型报错问题
问题根源
- Prop类型定义不匹配:初始赋值为null,但prop仅声明了
boolean | undefined,未包含null类型,Vue 3基于TS类型推导的运行时校验会因类型不符抛出错误。 - 非法修改只读Prop:模板中直接执行
modelValue = !modelValue属于修改单向只读的props,属于违规操作。 - 表单属性绑定错误:checkbox类型开关的选中状态需要绑定到
checked属性,而非value属性,value仅用于定义表单提交时的字段值,不控制选中状态。
修正代码
自定义开关组件 SwitchControl.vue
<template> <input ref="switchElement" v-bind="$attrs" class="gui-switch" @input="emit('update:modelValue', !modelValue)" type="checkbox" role="switch" :checked="!!modelValue" /> </template> <script setup lang="ts"> import { defineEmit, defineProps, onMounted, ref } from "vue" const props = defineProps<{ modelValue?: boolean | null }>() const emit = defineEmit<{ (e: "update:modelValue", value: boolean): void }>() const switchElement = ref<HTMLInputElement>() onMounted(() => { if (props.modelValue === null || props.modelValue === undefined) { switchElement.value!.indeterminate = true } }) </script>
父组件调用(无需额外修改)
<!-- v-for question in questions --> <switch-control :name="`question-${question.id}`" v-model="feedbackData[`question-${question.id}`]" :id="`question-${question.id}`" />
调整说明
- Prop类型新增null匹配初始值,同时设为可选属性,避免必填校验报错
- 删除模板中修改Prop的非法操作,仅通过emit事件触发父组件值更新
- 选中状态绑定改为
checked属性,用!!做布尔转换,兼容null/undefined初始值 - 调整半选状态触发逻辑,仅当初始值为空时显示indeterminate状态,符合交互逻辑
内容的提问来源于stack exchange,提问作者theberzi
相关产品推荐
相关产品推荐

