element select 多选全选功能

1、html部分

<el-select v-model="productLineIds" placeholder="请选择品线" size="small" clearable multiple collapse-tags @change="selectAll" >
      <el-option v-for="item in productLineOption" :label="item.name" :value="item.id" :key="item.id"></el-option>
</el-select>

2、data数据部分

productLineIds:[],//新值
oldproductLineIds:[],//旧值
productLineOption:[
{"id":74,"accountId":1,"name":"6111","parentId":61,"parentName":"61"},{"id":75,"accountId":1,"name":"6112","parentId":61,"parentName":"61"},{"id":76,"accountId":1,"name":"6113","parentId":61,"parentName":"61"},{"id":77,"accountId":1,"name":"6121","parentId":61,"parentName":"61"},{"id":78,"accountId":1,"name":"6122","parentId":61,"parentName":"61"},{"id":79,"accountId":1,"name":"6131","parentId":61,"parentName":"61"},{"id":80,"accountId":1,"name":"6132","parentId":61,"parentName":"61"}
],

3、js部分

selectAll (val) {
            const allValues = this.productLineOption.map(item => {
                return item.id;
            });
            // 用来储存上一次选择的值,可进行对比
            const oldVal = this.oldproductLineIds.length > 0 ? this.oldproductLineIds : [];
        
            // 若选择全部
            if (val.includes('all')) {
                this.productLineIds = allValues;
            }
        
            // 取消全部选中, 上次有, 当前没有, 表示取消全选
            if (oldVal.includes('all') && !val.includes('all')) {
                this.productLineIds = [];
            }
        
            // 点击非全部选中,需要排除全部选中 以及 当前点击的选项
            // 新老数据都有全部选中
            if (oldVal.includes('all') && val.includes('all')) {
                const index = val.indexOf('all');
                val.splice(index, 1); // 排除全选选项
                this.productLineIds = val;
            }
        
            // 全选未选,但是其他选项都全部选上了,则全选选上
            if (!oldVal.includes('all') && !val.includes('all')) {
                if (val.length === allValues.length - 1) {
                this.productLineIds = ['all'].concat(val);
                }
            }
        
            // 储存当前选择的最后结果 作为下次的老数据
            this.oldproductLineIds = this.productLineIds;
 }

版权声明:本文为weixin_44139784原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。