VUE el-select下拉框动态设置禁用,删除后恢复可选择
场景:点击新增添加按钮,列表table会新增一条包含下拉菜单的数据,如果其中任何一个下拉框选择了某个值,那么新增的下拉菜单的选项中该值是禁用状态,只能选择其他未被选中过的值。点击删除按钮后,已禁用的选项放开,可再次选择。
思路:在使用 <el-option>
组件时,如果你希望在选择某个选项后禁用它,可以通过动态绑定 disabled
属性来实现。这通常涉及到两个方面:
-
选择后的禁用:当用户选择了一个选项后,你需要更新这个选项的
disabled
状态。 -
动态绑定:使用 Vue 的响应式数据来动态控制
disabled
属性。
示例:
假设你有一个下拉选择框,用户选择后,希望该选项不再可用。
HTML 部分。
1、单个下拉
<template><el-select v-model="selected" placeholder="请选择" @change="change"><el-optionv-for="item in options":key="item.value":label="item.label":value="item.value":disabled="item.disabled"></el-option></el-select>
</template>2、循环多个下拉
<template>
<el-form ref="form" :model="formData" :inline="true" label-position="right"><el-button type="primary" @click="addCity">添加</el-button><div v-for="(item,index) in formData.cityList" :key="item.key"><el-form-item label="居住地" :prop="`cityList[${index}].city`" label-width="150" :rules="{ required: true, message: '请选择', trigger: 'blur'}"><span class="label" slot="label" v-if="!index"><template><em style="color: red">*</em></template>{{ lableName}}</span><el-select filterable clearable v-model="item.city" @change="cityChange(`cityList[${index}].city`, item)"><el-optionv-for="(child, idx) in cityOptions":value="child.value":label="child.label":key="idx":disabled="child.disabled"></el-option></el-select></el-form-item><el-button type="danger" @click="delCity(index)">删除</el-button></div><el-button type="primary" @click="subCity">提交</el-button>
</el-form>
</template>
JavaScript 部分
<script>
export default {data() {return {//单个数据selected: '', // 用户选择的选项options: [{ value: 'option1', label: '选项1' },{ value: 'option2', label: '选项2' },{ value: 'option3', label: '选项3' }],//多个数据lableName: '居住地',formData: {cityList: [{city: '',key: Date.now()}],},cityOptions: [{ value: 'Chengdu', label: '成都' },{ value: 'Shenzhen', label: '深圳' },{ value: 'Guangzhou', label: '广州' }],};},watch: {selected(newVal) {this.disableSelectedOption();}},methods: {方法一:单个select设置禁用disableSelectedOption() {this.options = this.options.map(option => {if (option.value === this.selected) {return { ...option, disabled: true }; // 禁用当前选中的选项}return option; // 其他选项保持不变});},方法二:批量添加后多个select设置禁用addCity() {this.formData.cityList.push({city: '',key: Date.now()})},delCity(index) {this.$confirm('确定删除?', '提示', {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning',}).then(() => {this.formData.cityList.splice(index, 1)this.disabledOptions()}).catch(() => {})},cityChange(name, item) {this.$refs.form.validateField(name) // 清除必填校验this.disabledOptions()},subCity() {this.$refs.form.validate(valid => {if (valid) {//todo} else {return false}})},disabledOptions() {this.cityOptions.forEach(item => {item.disabled = this.formData.cityList.some(row=> row.city=== item.value)})},}
}
</script>