You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3 script setup自定义输入组件v-model绑定缺required prop及类型报错问题

问题根源

  1. Prop类型定义不匹配:初始赋值为null,但prop仅声明了boolean | undefined,未包含null类型,Vue 3基于TS类型推导的运行时校验会因类型不符抛出错误。
  2. 非法修改只读Prop:模板中直接执行modelValue = !modelValue属于修改单向只读的props,属于违规操作。
  3. 表单属性绑定错误: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 13:48:02