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

Vue.js中v-for循环如何为首次迭代的单选框设置checked属性

实现方案

你当前用了v-model绑定单选框的选中状态,Vue会自动根据selectedChoice的值匹配单选框的value来控制选中状态,不需要手动操作checked属性,按以下步骤修改即可:

  1. 首先给单选框补全value属性绑定,这是v-model能正常识别选中状态的前提
  2. 初始化selectedChoice时直接赋值为options数组第一项的对应值即可

修改后的模板代码

<div v-for="(option) in options" :key="option.name">
  <label class="form-check-label mr-2" :for="option.for">
    {{ option.name }}
  </label>
  <input
    v-model="selectedChoice" 
    class="mr-4" 
    type="radio" 
    name="radio" 
    :id="option.for" 
    <!-- 绑定和selectedChoice匹配的value字段,可根据你的业务需求替换为option.name等其他字段 -->
    :value="option.for"
  />
</div>

初始化默认值示例

  • 选项式API:
data() {
  return {
    options: [/* 你的选项数据 */],
    // 取第一项的value作为初始值,空数组时做兼容处理
    selectedChoice: this.options.length ? this.options[0].for : ''
  }
}
  • 组合式API:
import { ref } from 'vue'

const options = ref([/* 你的选项数据 */])
const selectedChoice = ref(options.value.length ? options.value[0].for : '')

异步获取选项的特殊处理

如果options是从接口异步获取的,需要在拿到接口返回数据后再给selectedChoice赋值:

// 示例为组合式API的异步请求逻辑
async function fetchOptions() {
  const res = await fetch('/api/options')
  const data = await res.json()
  options.value = data
  // 拿到数据后再赋值初始选中值
  if (options.value.length) {
    selectedChoice.value = options.value[0].for
  }
}

内容的提问来源于stack exchange,提问作者Péah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 05:45:04