el-select动态禁用

在一个el-form表单中有5个el-form-item;

每个el-form-item是一个el-select控件;

这5个el-select控件遵循这样的规则,都是使用同一个list集合,如果第一个el-select选择了list中的某一项,那么这一项就被禁用;其他的el-selet就不能选择这一项了;

如果第二个el-select选择了list中的某一项,那么这一项和第一个el-select选择的项都禁用,

其他的el-select就不能选择这两项了;以此类推

<template>
  <div>
     <el-form :model='form' :rules="rules" ref="form">
      <el-form-item v-for="(select, index) in selects" :key="index" :label="'Select ' + (index + 1)"
                    prop="selectedOptions">
        <el-select v-model="form.selectedOptions[index]" @change="handleSelectChange(index)" @clear="handleSelectClear(index)" clearable>
          <el-option v-for="option in options" :key="option.value" :label="option.label" :value="option.value" :disabled="isOptionDisabled(option.value)"></el-option>
        </el-select>
      </el-form-item>
        <!-- <el-button type="primary" @click="submitForm">Submit</el-button> -->
    </el-form>
  </div>
</template>

Js代码:

<script>
export default {
  data() {
    return {
      options: [
        { label: 'Option 1', value: 1 },
        { label: 'Option 2', value: 2 },
        { label: 'Option 3', value: 3 },
        { label: 'Option 4', value: 4 },
        { label: 'Option 5', value: 5 }
      ],
      form:{
         selectedOptions: [null, null, null, null, null],
         disabledOptions: [], // 禁用的选项集合
      },
      rules: {
        selectedOptions: [
          { required: true, message: 'Please select at least one option', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    selects() {
      return Array.from({ length: 5 });
    }
  },
  methods: {
    // 下拉框选择事件
    handleSelectChange(index) {
      this.form.disabledOptions = [];
      console.log(this.form.selectedOptions,'+++++++ ')
      for (let i = 0; i < this.form.selectedOptions.length; i++) {
        if (this.form.selectedOptions[i] !== null) {
          this.form.disabledOptions.push(this.form.selectedOptions[i]);
        }
      }
    },
    // 下拉框清除事件
    handleSelectClear(index) {
      const clearedValue = this.form.selectedOptions[index];
      const indexToRemove = this.form.disabledOptions.indexOf(clearedValue);
      if (indexToRemove !== -1) {
        this.form.disabledOptions.splice(indexToRemove, 1);
      }
    },
    //是否禁用
    isOptionDisabled(value) {
      return this.form.disabledOptions.includes(value);
    }
  }
};
</script>

上一篇:FMEA助力新能源汽车行业腾飞:安全、效率双提升


下一篇:科技类媒体邀约资源有哪些?科技公司做活动如何做好宣传?