Vue中v-for渲染的多个select框无法存储多选项值问题求助
问题原因
你现在所有循环生成的<select>都绑定了同一个tailors数组,这会导致每次选择时,所有选择框的选中值都会被最后一次选择的值覆盖——因为它们共享同一个v-model绑定目标,没法区分每个选择框的独立选中状态。
解决方法
需要让每个<select>绑定到独立的存储位置,可以用对象来映射每个gettailor的唯一id和对应的选中值,这样每个选择框的状态就不会互相干扰。
具体修改步骤
- 把存储选中值的
tailors从数组改成对象,用来按gettailor.id存储对应选中值 - 给每个
<select>和对应的<label>设置动态唯一ID,避免重复ID导致的label关联问题 - 将每个
<select>的v-model绑定到tailors[gettailor.id],让每个选择框对应对象里的独立属性
修改后的完整代码
<template v-for="(gettailor) in gettailors" :key="gettailor.id"> <div class="col-sm-6"> <div class="form-floating"> <p>{{ gettailor.names }}</p> </div> </div> <div class="col-sm-6"> <div class="form-floating"> <!-- 动态设置唯一ID,绑定到对象的对应属性 --> <select class="form-select shadow-none" :id="`tailors-${gettailor.id}`" v-model="tailors[gettailor.id]" required> <template v-for="(item) in gettailor.tailor" :key="item.id"> <option :value="item.id">{{ item.tailor }}</option> </template> </select> <!-- label的for属性对应动态ID --> <label :for="`tailors-${gettailor.id}`">Choose {{ gettailor.names }}</label> </div> </div> </template> <script> import { ref, watch, onMounted } from 'vue'; // 改成对象存储,key是gettailor的id,value是对应选中的item.id const tailors = ref({}); </script>
补充说明
- 如果之后需要把选中值转换成数组格式,可以用
Object.values(tailors.value)来获取所有选中的id数组 - 要是你更习惯用数组存储,可以初始化一个和
gettailors长度一致的数组,然后v-model绑定tailors[index](需要在v-for里加上index参数:v-for="(gettailor, index) in gettailors"),但用对象按id存储的方式更健壮,不会因为gettailors的顺序变化导致数据错位
内容的提问来源于stack exchange,提问作者Martín
相关产品推荐
相关产品推荐

