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

Vue下拉框选中值无法更新,始终获取默认值问题求助

Vue下拉框选中值无法更新的问题解决

问题根源分析

  1. 初始化错误:你在data里用selectedType: this.type初始化,但组件接收的props是cabin,正确的初始化应该指向this.cabin.type。
  2. v-model与手动selected属性冲突:<option>标签上的:selected="selectedType = cabin.type"是核心问题——这个赋值语句会在每一次渲染选项时执行,强制把selectedType重置为cabin.type,直接覆盖用户的选择。Vue的v-model已经会自动绑定下拉框的选中状态,完全不需要手动设置selected属性。

修正后的代码

模板部分

<select v-model="selectedType" @change="onTypeChange">
  <option v-for="type in types" :key="type" :value="type">
    {{ type }}
  </option>
</select>

脚本部分

export default {
  name: 'CabinsDetail32',
  props: ['cabin'],
  data() {
    return {
      types: [
        'GEAR',
        'SMALLDT',
        'SMALL',
        'LARGE',
        'FAMILY'
      ],
      selectedType: this.cabin.type // 修正初始值来源
    }
  },
  methods: {
    onTypeChange() {
      // 直接通过this.selectedType获取最新选中值
      console.log('当前选中类型:', this.selectedType)
    }
  }
}

额外注意事项

  • 确保cabin.type的初始值存在于types数组中,否则下拉框会默认无选中项。如果需要兼容cabin.type不在数组的情况,可以在初始化时做判断:
    selectedType: this.types.includes(this.cabin.type) ? this.cabin.type : this.types[0]
    
  • 如果你只是需要获取选中值,@change事件不是必须的——v-model会自动同步selectedType的值,任何时候直接访问this.selectedType就能拿到最新结果。

内容的提问来源于stack exchange,提问作者wilco van de pol

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 15:25:07