现在有一个问卷调查页面的需求,选择了element-ui的el-checkbox-group来处理多选题,在有多个多选题的情况下,如何绑定v-model数据才能获取到 问题id=>对应问题下选中的选项
question.vue页面
<template>
<div>
<el-form class="custom-form" ref="form" :model="temp" label-width="100px" status-icon @submit.native.prevent>
<div class="question" v-for="(item,index) in dataList">
<div class="question-item">
<div class="item-item">
<div class="item-title"><span class="stars" v-if="item.must_fill===1">*</span> {{item.title}} (多选)</div>
<el-form-item class="custom-form-item">
<el-checkbox-group class="custom-group"
v-model="temp[item.id]" @change="OnCheckBoxChange(item.id)">
<el-checkbox class="custom-box"
v-for="(key,index) in item.items"
:label="key.id"
:key="key.id"
>{{key.title}}</el-checkbox>
</el-checkbox-group>
</el-form-item>
</div>
</div>
<!--提交按钮-->
<el-form-item>
<el-button type="primary" @click="handleSubmit">提交</el-button></el-form-item>
</el-form>
</div>
<script>
export default{
data(){
return{
temp:[]
}
},
props:{
dataList:{
type:Array
}
},
methods:{
OnCheckBoxChange(key){
console.log(key)
},
async handleSubmit(){
console.log(this.temp)
this.$emit('submit', this.temp)
}
},
}
</script>
这是传递过来的dataList:
[
{
"id": 1,
"title": "问题1",
"paperid": 1,
"must_fill": 1,
"type": 1,
"status": 1,
"items": [
{
"id": 5,
"title": "选项一",
},
{
"id": 6,
"title": "选项二",
},
{
"id": 7,
"title": "选项三",
},
{
"id": 8,
"title": "选项四",
}
]
},
{
"id": 2,
"title": "问题2",
"paperid": 1,
"paperid": 1,
"must_fill": 1,
"type": 1,
"status": 1,
"items": [
{
"id": 2,
"title": "选项二",
},
{
"id": 1,
"title": "选项一",
},
{
"id": 3,
"title": "选项三",
},
{
"id": 4,
"title": "选项四",
}
]
},
]
这里我把<el-checkbox-group>中v-model写成以下形式:
<el-checkbox-group class="custom-group"
v-model="temp[item.id]" @change="OnCheckBoxChange(item.id)">
发现会报错,vue.runtime.esm.js:619 [Vue warn]: Error in render: "TypeError: Cannot read property 'length' of undefined"
怀疑是数据的问题,element-ui官网表示checkboxgroup必须的是数组,
但是如何区分不同的<el-checkbox-group>呢?数据有多个<el-checkbox-group>,怎么区分el-checkbox-group而且获取dataList中的问题id,让它们以问题id=>对应问题下选中的选项进行提交,类似于这种
{
1:[3,4],//1是问题id,[3,4]是选中的多选选项
2:[7,8]
}
element 官网的示例