elementUI动态表单 + el-select 按要求禁用问题

Adeline ·
更新时间:2024-09-20
· 238 次阅读

目录

先实现最简单的:限制新增数量

下拉菜单已选中的选项 禁用

移除后要把移除的那条选中项的disabled 设为false

完整代码

项目通过 vue+elementUI 实现

近期开发过程中遇到一个需求,对于从事两年的“小白”来说,确实费了点脑子,才发现,好像是自己一开始想太多了,各种情况设想了一溜够,发现只要反过来想就OK了 ╮(╯▽╰)╭

需求大概是这样的:

在动态增减的表单项中,有一个下拉菜单,要求每选择一项,就把选中过的那一个选项禁用(简单来说就是,已经选过的就不能再选了),且增加的条数不能超过下拉菜单中的选项数量

直接上图吧(label不重要,主要看效果。。。)

先实现最简单的:限制新增数量

判断已新增的数量是否小于下拉菜单中选项的数量

如果小于就新增,否则可以提示一些信息(这里就忽略不写了)

// 新增按钮绑定的 的方法 addType () { if (this.otherForm.other.length < this.typeList.length) { this.otherForm.other.push({ type: '', key: Date.now() }) } } 下拉菜单已选中的选项 禁用

逻辑很简单,当下拉菜单 change 时,先把所有下拉菜单选项的 disabled 赋值为 false(这里用到排他思想,每次change 都先不禁用,选了哪个禁用哪个),遍历存储表单数据的数组,在下拉菜单的 list 中找到对应的当前被选中的项,将该项的 disabled 设为 true(简单来说就是 现在都有哪项被选择了 就禁用它 )

changeType (index, Id) { this.typeList.forEach(v => { v.disabled = false for (var i = 0; i < this.otherForm.other.length; i++) { if (this.otherForm.other[i].type === v.Id) { v.disabled = true } } }) } 移除后要把移除的那条选中项的disabled 设为false // 移除按钮 绑定事件 removeType (item) { var index = this.otherForm.other.indexOf(item) if (index !== -1) { this.otherForm.other.splice(index, 1) } // 在下拉菜单数据中找到移除的那条的选中项 赋值为false this.typeList.forEach(v => { if (v.Id === item.type && v.disabled) { v.disabled = false } }) } 完整代码 <template> <div> <el-form :model="otherForm" ref="otherForm" label-width="100px"> <el-form-item v-for="(other, index) in otherForm.other" :label="'类型' + index" :key="index" :prop="'other.' + index + '.type'"> <el-select v-model="other.type" placeholder="请选择" @change="changeType(index, other.type)"> <el-option v-for="item in typeList" :key="item.Id" :label="item.label" :value="item.Id" :disabled="item.disabled"> </el-option> </el-select> <el-button @click.prevent="removeType(other)">删除</el-button> </el-form-item> <el-form-item> <el-button @click="addType">新增</el-button> </el-form-item> </el-form> </div> </template> <script> export default { data () { return { otherForm: { other: [{ type: '' }] }, typeList: [{ Id: 1, label: '报名费' }, { Id: 2, label: '饭费' }, { Id: 3, label: '餐费' }, { Id: 4, label: '书本费' }] } }, methods: { // 删除 removeType (item) { var index = this.otherForm.other.indexOf(item) if (index !== -1) { this.otherForm.other.splice(index, 1) } this.typeList.forEach(v => { if (v.Id === item.type && v.disabled) { v.disabled = false } }) }, // 新增 addType () { if (this.otherForm.other.length < this.typeList.length) { this.otherForm.other.push({ type: '', key: Date.now() }) } }, changeType (index, Id) { this.typeList.forEach(v => { v.disabled = false for (var i = 0; i < this.otherForm.other.length; i++) { if (this.otherForm.other[i].type === v.Id) { v.disabled = true } } }) } } } </script>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持软件开发网。



表单 select

需要 登录 后方可回复, 如果你还没有账号请 注册新账号