vue中怎么处理多个单选框,且单选框互不影响的方案
项目需求是:需要提交多个老师的信息,信息中包含老师的职位,职位是单选框;
难点是:怎么确保多个单选框不冲突,单选框怎么用v-for遍历出来;
最终效果是:
1、首先最外层先通过数组遍历出来,数组结构需要加上老师名称和手机号,便于保存,具体结构如下:
teacherList: [ { name: '一', role: 1, teacherName: '', phone: null }, { name: '二', role: 1, teacherName: '', phone: null }, { name: '三', role: 1, teacherName: '', phone: null } ]
解释一下:name是用来显示是第几位老师,role默认值为1,是职位默认为主管,后面的name和phone是用来保存每个老师的信息;
<div> <img class="teacher-img" src="../../common/image/teacher.png" alt=""> <span class="teacher-title">第{{item.name}}位辅导老师</span> </div> <div> <input v-model="item.teacherName" class="teacher-name" type="text" maxlength="8" placeholder="请输入辅导老师的姓名"> </div> <div> <input type="number" v-model="item.phone" pattern="[0-9]*" class="teacher-name" placeholder="请输入辅导老师的手机号"> </div>
2、遍历单选框的职位,注意用teacherList中的role保存每个老师选择的职位,这样才不会出现冲突;
单选框的数组结构如下:
positionList: [ { name: 'AI主管', role: 1 }, { name: 'AI辅导老师', role: 2 } ]
html代码如下:
<label class="select-label" :class="{'mr': index == 0}" v-for="(_item, index ) in positionList" :key="_item.role"> <img v-if='item.role == _item.role ' class="select-radio" src="../../common/image/select2.png" alt=""> <img v-else class="select-radio" src="../../common/image/select1.png" alt=""> <input @click="selectPosition(_index, _item.role)" type="radio" name="radios" :value="_item.role"> <span>{{_item.name}}</span> </label>
解释一下:v-if是判断teacherList中的role和positionList中的role是否一致,显示选中/未选中效果,每次点击input单选框后,将当前的role赋值给teacherList中的role保存;
完整代码如下:
<div class="teacher" v-for="(item, _index) in teacherList" :key="_index"> <div> <img class="teacher-img" src="../../common/image/teacher.png" alt=""> <span class="teacher-title">第{{item.name}}位辅导老师</span> </div> <div> <input v-model="item.teacherName" class="teacher-name" type="text" maxlength="8" placeholder="请输入辅导老师的姓名"> </div> <div> <input type="number" v-model="item.phone" pattern="[0-9]*" class="teacher-name" placeholder="请输入辅导老师的手机号"> </div> <p class="teacher-select-title">请选择辅导老师职位</p> <div class="teacher-select"> <label class="select-label" :class="{'mr': index == 0}" v-for="(_item, index ) in positionList" :key="_item.role"> <img v-if='item.role == _item.role ' class="select-radio" src="../../common/image/select2.png" alt=""> <img v-else class="select-radio" src="../../common/image/select1.png" alt=""> <input @click="selectPosition(_index, _item.role)" type="radio" name="radios" :value="_item.role"> <span>{{_item.name}}</span> </label> </div> </div>
js赋值代码如下:
selectPosition (index, role) { this.teacherList[index].role = role },
最后再从positionList中将需要的数据提取出来即可;
注意:如果需求是不必填写所有老师,有至少一个信息完成的就可以提交的话,遍历positionList的时候用some函数,不要用foreach;因为如果两个老师信息填写不全,一个老师信息正常,你在做错误提示的时候,肯定只提示一下就可以,但是foreach会遍历所有的对象,会出现两次报错;