下拉框互斥,即:同时有多个下拉框,可选内容option是相同的,有一个下拉框选了某项,其他下拉框将不能再进行选择。
1.首先需要4个el-select下拉框,该文章讲的是单选的下拉框,如果需要多选下拉框互斥,请移步我的主页看(vue+elementui可多选的el-select下拉框的互斥问题)。
<el-form label-width="80px">
<el-form-item label="爱好1">
<el-select v-model="hobby.hobby1" @change="changeSelect">
<el-option
v-for="(item,index) in hobbyList"
:key="index"
:label="item.value"
:value="item.value"
:disabled="item.disabled"
></el-option>
</el-select>
</el-form-item>
<el-form-item label="爱好2">
<el-select v-model="hobby.hobby2" @change="changeSelect">
<el-option
v-for="(item,index) in hobbyList"
:key="index"
:label="item.value"
:value="item.value"
:disabled="item.disabled"
></el-option>
</el-select>
</el-form-item>
<el-form-item label="爱好3">
<el-select v-model="hobby.hobby3" @change="changeSelect">
<el-option
v-for="(item,index) in hobbyList"
:key="index"
:label="item.value"
:value="item.value"
:disabled="item.disabled"
></el-option>
</el-select>
</el-form-item>
<el-form-item label="爱好4">
<el-select v-model="hobby.hobby4" @change="changeSelect">
<el-option
v-for="(item,index) in hobbyList"
:key="index"
:label="item.value"
:value="item.value"
:disabled="item.disabled"
></el-option>
</el-select>
</el-form-item>
</el-form>
2.给下拉框绑定数据,有4个下拉框,所以要绑定4个值,放到一个hobby对象中,可以看的更加清楚明了,hobby1,hobby2,hobby3,hobby4为参照属性。
hobby1: '',
hobby2: '',
hobby3: '',
hobby4: '',
hobby: {//el-select绑定的对象
hobby1: '',
hobby2: '',
hobby3: '',
hobby4: ''
},
hobbyList: [//下拉框遍历option
{value: '001', disabled: false},
{value: '002', disabled: false},
{value: '003', disabled: false},
{value: '004', disabled: false},
{value: '005', disabled: false},
{value: '006', disabled: false}
]
3.编写方法,仅需要一个change方法,通过操作hobby对象,来控制下拉框选option的disabled属性。
changeSelect (val) {
// 先把hobbyList恢复默认值,即所有的选项都是可选
this.hobbyList.forEach(item => {
item.disabled = false
})
// 判断hobby对象中,哪个属性发生了变化
// 将选中值val直接赋值给发生变化的值,更新hobby对象
if (this.hobby.hobby1 !== this.hobby1) {
this.hobby.hobby1 = val
} else if (this.hobby.hobby2 !== this.hobby2) {
this.hobby.hobby2 = val
} else if (this.hobby.hobby3 !== this.hobby3) {
this.hobby.hobby3 = val
} else if (this.hobby.hobby4 !== this.hobby4) {
this.hobby.hobby4 = val
}
// 对hobby对象遍历,hobby中有哪一项,就把hobbyList中该项的disabled属性变为true,禁用
for (var key in this.hobby) {
this.hobbyList.forEach(item => {
if (this.hobby[key] === item.value) {
item.disabled = true
}
})
}
// 把hobby对象的值暂时存一下,作为参照,分别存到hobby1,hobby2,hobby3.hobby4中
this.hobby1 = this.hobby.hobby1
this.hobby2 = this.hobby.hobby2
this.hobby3 = this.hobby.hobby3
this.hobby4 = this.hobby.hobby4
}