el-select多选条件下添加【全选】的问题

背景:

页面中有10个select 多选框,要为每一个多选框 添加一个多选的option 来实现多选的功能

方法一

为每一个多选框单独添加多选

`

<el-tooltip content="支持多选" placement="top">
        <el-form-item>
          <el-select
            v-model="form.exam"
            placeholder="请选择考试"
            multiple
            collapse-tags
            clearable
            @change="changeExam"
          >
            <el-option label="全选" value="全选" @click.native="selectAll()"></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>
      </el-tooltip>

`

`

 selectAll() {
    console.log(this.form.exam,this.exam);
    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("全选");
      console.log(this.form.exam);
    } else {
      this.form.exam = [];
    }
  },

`
这种情况下 可是实现多选效果,但是缺点就是要为每一个select单独添加一个 全选功能,很冗余
实现效果如下

image.png

方法二

封装一个全选方法,传递参数

`

 <el-tooltip content="支持多选" placement="top">
        <el-form-item>
          <el-select
            v-model="form.exam"
            placeholder="请选择考试"
            multiple
            collapse-tags
            clearable
            @change="changeExam"
          >
            <el-option label="全选" value="全选" @click.native="selectAll(form.exam,exam)"></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>
      </el-tooltip>

`
`

 selectAll(selectedArray, options) {
    console.log(selectedArray, options);
    if (selectedArray.length < options.length) {
      selectedArray = [];
      options.map((item) => {
        selectedArray.push(item.id);
      });
      selectedArray.unshift("全选");
      console.log(123,selectedArray)
    } else {
      selectedArray = [];
    }
  },

`
这种情况下实现的效果如下 选项没有勾选的效果,让用户没有一是到是全选 但是感觉这两个方法一模一样啊 打印的数据都一样

image.png

很费解
是我哪里写的不对吗?我感觉是方法二传递参数的问题
有什么好方法 可以实现封装一个全选的方法

阅读 4.2k
2 个回答
selectAll(selectedArray, options) {
    if (selectedArray.length < options.length) {
        options.map((item) => {
            selectedArray.push(item.id);
        });
    } else {
        selectedArray.splice(0, selectedArray.length);
    }
}

改成这样就好了

this.form.exam.length < this.exam.length
selectedArray.length < options.length

你好好看看,想想

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题