Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

el-select 全选+change事件,该如何简化跟封装

背景:
select 多选 并且添加一个全选按钮,每一次选择,包括选择 单选 多选,全选 取消全选 都要调用接口 select之间逐级联动,页面上一共10个select 彼此逐级联动

现在实现,其中一个例子如下

`

 <el-form-item>
          <el-select
            v-model="form.exam"
            placeholder="请选择考试"
            multiple
            ref="exam"
            collapse-tags
            clearable
            @change="changeExam"
          >
            <el-option label="全选" value="全选" @click.native="selectAllExam"></el-option>
            <el-option v-for="item in exam" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

`

以下方法可以实现 需求 但是目前页面上有10个select 要写10个全选方法 9个 change方法 十分冗余 请问 有什么方法可以简化或者封装的,曾经试过把全选 跟 change写在一起 但是bug比较多

`

 //全选考试
  selectAllExam() {
    if (this.form.exam.length < this.exam.length) {
      this.form.exam = [];
      this.exam.map((item) => {
        this.form.exam.push(item.id);
      });
      this.form.exam.unshift("全选");
    } else {
      this.form.exam = [];
    }
  },
  // 考试筛选年份
  changeExam(val) {
    console.log(12, val);
    this.form.year = "";
    this.form.season = "";
    this.form.paper = "";
    this.form.type = "";
    this.form.groupId = "";
    let data = [];
    data = val;
    if (!val.includes("全选") && val.length === this.exam.length) {
      this.form.exam.unshift("全选");
      data = [];
    } else if (val.includes("全选") && val.length - 1 < this.exam.length) {
      this.form.exam = this.form.exam.filter((item) => {
        return item !== "全选";
      });
      this.exam.map((item) => {
        data.push(item.id);
      });
    }
    this.$axios.post(`/api/tabYear/getYearByExam.json`, data).then((res) => {
      if (res.success) {
        this.year = res.result;
      } else {
        this.$message.error(res.message);
      }
    });
  },

`


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

全选等同于把所有值都选上,应该不会影响各个select或者后端交互的逻辑

  1. 封装一个包含全选的select组件,处理单个组件内全选的所有逻辑
  2. 组件之前的联动不考虑全选,只关心不同值之间的联动

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...