前言:最近在做项目,有个做题的需求,分别有单选题,多选题,问答题,三种题型。因为题的数量不确定,所以肯定是for 循环每一道题,完了之后发现有问题;

问题:

for循环之后,就会发现,这三种组件( el-checkbox-group,el-radio-group,el-input)以下简称组件。都是只绑定一个变量,来获取当前的值,所以for循环之后绑定的值是一样的,导致出现bug;例如下面的v-model 绑定的值:其余组件一样,不做重复介绍

<div v-for="(item,index) in questions" :key="index">
                        <div class="tj_team fen_team" v-if="item.type==2">  <!--单选问题-->
                            {{item.sort}}.&nbsp;&nbsp;{{item.description}}?(单选) <br>
                            <el-radio-group v-model="checkList[item.id]" class="w_radio">
                                <el-radio :label="i.id" v-for="(i,d) in item.options" :key="d">{{i.sort}}{{i.explain}}
                                </el-radio>
                            </el-radio-group>
                        </div>
</div>

解决:

只要把绑定的值变成一个对象就可以了,例如我上面的写法。由于我的需求是答题:所以我的思路是把当前题的id 变成当前对象  键名(每个对象的键名为当前题到id,对象的键值为当前题的答案);代码如下:

先在data中初始化checkList 为{}    空对象;下面为重点,必须使用$set,因为vue 不能检测对象动态添加的属性值,所以提供了$set方法;

for (var i = 0; i < this.questions.length; i++) {
                            if (this.questions[i].type == 1) {   //问答题   让当前对象的键名 为当前题的id
                                this.$set(this.checkList, this.questions[i].id, '')
                            }
                            if (this.questions[i].type == 3) {   //多选题
                                this.$set(this.checkList, this.questions[i].id, [])
                            }
                            if (this.questions[i].type == 2) {     //单选题
                                this.$set(this.checkList, this.questions[i].id, '')
                            }
                        }

最后只需要for in 循环这个checkList ,把相应的值组成数组传给后台即可;

Logo

前往低代码交流专区

更多推荐