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

Vue3使用v-for生成下拉列表时selected属性不生效问题

原因说明

给<select>元素绑定v-model后,Vue会完全接管下拉框的选中状态控制逻辑,手动给<option>绑定的:selected属性会被v-model的逻辑覆盖,不会被渲染到DOM上,也不会生效。
你把绑定属性换成自定义的:foo能正常渲染,是因为foo不属于表单元素的内置状态属性,Vue不会对它做特殊处理,会按照普通属性规则直接渲染到DOM;但selected是<option>标签的原生内置选中属性,属于v-model的管控范围,Vue只会根据v-model绑定的变量值判断哪个选项应该被选中,不会读取你手动绑定的selected属性值。

修复方案

不需要手动给option绑定selected属性,只需要在组件初始化阶段,把v-model绑定的selected变量的初始值设置为目标默认选项的value(也就是对应项的uri值)即可,v-model会自动匹配value和绑定值相等的选项,将其设为选中状态并渲染selected属性。

参考实现代码:

// 脚本逻辑中初始化选中值
import { ref } from 'vue'
const selected = ref('')

// 拿到资源类型数据后,查找标记为默认选中的项
const initDefaultSelected = () => {
  const defaultItem = resourcesTypesData.ResourcesTypes.find(item => item.selected)
  if (defaultItem) {
    selected.value = defaultItem.uri
  }
}
// 数据加载完成后调用初始化方法即可

模板部分删除多余的:selected绑定即可:

<template>
  <div class="dropdown">
    <select v-model="selected" @change="onChangeMethod($event)">
      <option disabled value="">Sélectionnez le type de ressources</option>
      <option 
        v-for="resourceType in resourcesTypesData.ResourcesTypes" 
        :key="resourceType.uri"
        :value="resourceType.uri"
      >
         {{ resourceType.label }}
       </option>
    </select>
  </div>
</template>

注意:只有在select标签未绑定v-model的场景下,手动给option绑定:selected才会正常生效。只要使用了v-model,下拉框的所有选中状态都要以v-model绑定的变量值为唯一判断标准,不要手动操作option的selected属性,避免逻辑冲突。

内容的提问来源于stack exchange,提问作者Philippe G.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 03:31:00