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

Vue.js:如何在页面渲染时默认选中指定单选按钮?

解决Vue单选按钮默认选中不生效的问题

我来帮你搞定这个问题~你遇到的情况是因为Vue的v-model和原生的checked属性不能同时使用,v-model会完全接管单选按钮的选中状态,你手动设置的:checked="property.checked"会被v-model覆盖掉,所以导致所有按钮都没选中。

正确的解决思路

不用依赖property.checked来控制选中状态,而是直接把v-model绑定的picked2初始化为默认选中项的index即可。

具体实现步骤

  1. 先找到propertiesList中checked值为'checked'的那一项的索引
  2. 把picked2的初始值设置为这个索引

举个例子:
如果是Vue2的选项式API:

<script>
export default {
  data() {
    return {
      propertiesList: [
        { address: '地址1', checked: null },
        { address: '地址2', checked: 'checked' },
        { address: '地址3', checked: null }
      ],
      picked2: null
    }
  },
  created() {
    // 找到默认选中项的index
    const defaultIndex = this.propertiesList.findIndex(item => item.checked === 'checked')
    // 初始化picked2
    this.picked2 = defaultIndex !== -1 ? defaultIndex : null
  }
}
</script>

<template>
  <template v-for="(property, index) in propertiesList" :key="index">
    <input type="radio" :value="index" v-model="picked2">
    {{ property.address }}<br>
  </template>
</template>

如果是Vue3的组合式API:

<script setup>
import { ref, onMounted } from 'vue'

const propertiesList = ref([
  { address: '地址1', checked: null },
  { address: '地址2', checked: 'checked' },
  { address: '地址3', checked: null }
])
const picked2 = ref(null)

onMounted(() => {
  const defaultIndex = propertiesList.value.findIndex(item => item.checked === 'checked')
  picked2.value = defaultIndex !== -1 ? defaultIndex : null
})
</script>

<template>
  <template v-for="(property, index) in propertiesList" :key="index">
    <input type="radio" :value="index" v-model="picked2">
    {{ property.address }}<br>
  </template>
</template>

这样修改后,页面渲染时对应的单选按钮就会默认选中啦~另外记得给v-for加上:key属性,这是Vue的最佳实践哦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:47:30