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

Vue3中如何将动态对象属性绑定到v-model实现单选框绑定?

问题分析与解决方案

你的问题核心出在三个关键细节上:单选框组命名冲突、默认事件被阻止、响应式属性初始化方式错误,以下是具体修复方案:

1. 给每个问题的单选框设置独立分组

所有单选框共用name="lifetime"会导致它们归为同一组,只能选中一个选项。需要为每个问题的单选框组设置唯一名称,比如绑定为lifetime-question.id:

<tr v-for="question in questions"
    :class="{'table-active': question.id === currentQuestionId}"
    @click.prevent="currentQuestionId = question.id">
  <td class="cursor-pointer">{{ question.text }}</td>
  <td class="text-center">
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" value="y" 
             v-model="lifetime[question.id]"
             :name="`lifetime-${question.id}`">
      <label class="form-check-label">Yes</label>
    </div>
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" value="n"
             v-model="lifetime[question.id]"
             :name="`lifetime-${question.id}`">
      <label class="form-check-label">No</label>
    </div>
  </td>
</tr>

2. 移除多余的点击事件

v-model本身已经实现了数据与视图的双向绑定,你添加的@click.prevent会阻止单选框的默认选中行为,导致视图无法同步选中状态。直接删除该事件即可。

3. 正确初始化响应式属性

在Vue3的Options API中,直接给对象添加新属性无法触发响应式更新,需要用this.$set来初始化lifetime的属性:

data() {
  return {
    questions: [], // 你的问题列表数据
    currentQuestionId: null,
    lifetime: {} // 初始化为空响应式对象
  }
},
mounted() {
  this.questions.forEach(q => {
    // 使用$set确保新添加的属性具备响应式能力
    this.$set(this.lifetime, q.id, '');
  });
},
methods: {
  // 完全移除updateAnswer方法,v-model会自动处理数据同步
}

问题根源总结

  • 相同的name属性导致单选框组冲突,无法独立选择每个问题的选项
  • @click.prevent阻止了单选框的默认选中逻辑,即使数据更新,视图也不会显示选中状态
  • 直接给lifetime对象添加属性未触发Vue的响应式检测,导致v-model无法正常工作

修改后,每个问题的单选框可以独立选择,v-model会自动同步lifetime对象中的数据,视图也会正确显示选中状态。

内容的提问来源于stack exchange,提问作者Nathan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 11:27:28