Vue.js中v-for循环如何为首次迭代的单选框设置checked属性
实现方案
你当前用了v-model绑定单选框的选中状态,Vue会自动根据selectedChoice的值匹配单选框的value来控制选中状态,不需要手动操作checked属性,按以下步骤修改即可:
- 首先给单选框补全
value属性绑定,这是v-model能正常识别选中状态的前提 - 初始化
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
相关产品推荐
相关产品推荐

