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

如何通过v-model获取ion-select选中值?基于v-for绑定drinkName

Ionic Vue 实现 ion-select 选中值绑定

你的核心代码逻辑是正确的,要确保绑定生效并正常获取选中值,需要注意以下几个细节:

1. 正确声明响应式变量

必须在组件中初始化drinkName和drinks数组,确保它们是Vue的响应式变量:

<script setup>
import { ref } from 'vue';
import { IonSelect, IonSelectOption } from '@ionic/vue';

// 初始化选中值,可设为空字符串或默认选项值
const drinkName = ref('');
// 示例饮品数据
const drinks = ref([
  { name: 'Coffee' },
  { name: 'Tea' },
  { name: 'Juice' }
]);
</script>

2. 优化:key的使用(推荐)

尽量避免用数组索引作为:key,如果后续对drinks数组进行增删操作,索引作为key可能导致组件渲染异常。建议使用每个饮品的唯一标识(比如新增id字段):

<ion-select-option
  v-for='drink in drinks'
  :key='drink.id' <!-- 用唯一id替代index -->
  :value="drink.name"
>{{ drink.name }}</ion-select-option>

3. 验证绑定效果

可以在模板中添加调试文本,实时查看选中值的变化:

<p>当前选中:{{ drinkName }}</p>

完整可运行示例

<template>
  <ion-page>
    <ion-content class="ion-padding">
      <ion-select v-model='drinkName' placeholder="选择饮品">
        <ion-select-option
          v-for='drink in drinks'
          :key='drink.id'
          :value="drink.name"
        >{{ drink.name }}</ion-select-option>
      </ion-select>
      <p class="ion-margin-top">选中的饮品:{{ drinkName }}</p>
    </ion-content>
  </ion-page>
</template>

<script setup>
import { ref } from 'vue';
import { IonPage, IonContent, IonSelect, IonSelectOption } from '@ionic/vue';

const drinkName = ref('');
const drinks = ref([
  { id: 1, name: '美式咖啡' },
  { id: 2, name: '红茶' },
  { id: 3, name: '橙汁' }
]);
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 10:45:44