1,需求:
在开发中,我们会遇到动态渲染下拉选择框,每次点新增按钮,列表typeList就会新增一条可以选择的下拉菜单,如果一个下拉菜单选中了其中一个值A,那么新增之后的下拉菜单的A是就不允许再次选中了,需用我们前端禁用掉不允许选中。
实现:
1,首先把下拉菜单的options拿到,,把里面的每一项新增一个item.disabled=false的属性,这样可以去控制下拉框是否禁用。
this.$store.dispatch('pm/GetBrandList', { ...this.BrandListForm, ...page }).then(res => {
this.projectListOptions = res.pocket.projectList
this.projectListOptions.forEach(item => {
item.disabled = false
})
})
2,在下拉框值改变的时候我们写一个方法用来监听,如果选中的值和从接口拿到列表数据做对比。判断是否有相同的,有的话就把列表数据对应值禁用掉。
注:这里两个地方需要用到的,【1,下拉框值改变调用此方法,2,删除对应一项下拉框时候调用此方法】
// 项目名称选中不可以重复选择
projectnameChange (val) {
const findItem = this.projectListOptions.find(e => e.projectId === val)
// 添加其他参数值例如再项目名称后面加客户名称custmtomerName
this.addcocorporationName = findItem?.custmtomerName
this.getprojectlistdisabled(val)
},
// 获取是否有禁用数据给disabled
// 思路分析:1,准备一个空数组用来存放当前选中后下拉框值---typesarry ;
// 2, 然后遍历接口拿到的下拉框列表数据去进行遍历拿到对应value值,拿到后和我们存放选中的下拉框进行比对是否有相同的value值,有的话就disabled为true表示已经选择过不允许再次选中。
getprojectlistdisabled () {
const typesarry = []
this.BrandForm.projectNameArry.forEach(item => {
if (item.value) {
typesarry.push(item.value)
}
})
this.projectListOptions.forEach(element => {
if (typesarry.indexOf(element.value) !== -1) {
element.disabled = true
// 这里是添加额外的参数custmtomerName用来显示在项目名称旁边的
if (val) {
this.BrandForm.projectNameArry.forEach(itemchild => {
if (val === itemchild.projectId) {
itemchild.custmtomerName = this.addcocorporationName
}
})
}
} else {
element.disabled = false
}
})
},
3,渲染动态下拉框如下
<div v-if="BrandForm.projectNameArry.length > 0">
<div v-for="(item, index) in BrandForm.projectNameArry" :key="index">
<el-form-item label="项目名称" :prop="'projectNameArry.'+ index +'.value' " :rules="{ required: true, message: '请选择项目名称', trigger: 'blur' }" class="subsettypebox">
<el-select
clearable
filterable
v-model="item.value"
@change="projectnameChange"
placeholder="请选项目名称">
<el-option
v-for="item in projectListOptions"
:key="item.value"
:label="item.label"
:disabled="item.disabled"
:value="item.value">
</el-option>
</el-select>
<i @click="addproductClick(item)" class="btn-group el-icon-circle-plus-outline"></i>
<i @click="removproductClick(index)" class="btn-group del el-icon-delete" v-show="BrandForm.projectNameArry.length > 1"></i>
</el-form-item>
</div>
</div>
// 新增项目名称
addproductClick (item) {
if (!item.value) {
this.$message.warning('请先选择项目名称再进行新增操作!')
} else {
this.BrandForm.projectNameArry.push({
value: ''
})
}
},
removproductClick (index) {
this.BrandForm.projectNameArry.splice(index, 1)
this.getprojectlistdisabled()
},