继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【组件封装】改造 Element-UI 多选框组件 (el-checkbox)

surewinT
关注TA
已关注
手记 4
粉丝 0
获赞 2

el-checkbox多选框组件

element-ui官网的多选框组件,是采用简单数组进行配置的,显示的lable值与勾选后的值是同一个

9e63b6d3e09747bdbd1220a19e9fdcbe~tplv-k3

实际业务场景

在实际业务开发中,我们更多遇到是如下数组对象的格式。
我们需要额外将数组进行label、value的拆分才能使用 el-checkbox 。
如果要实现勾选、全选、默认赋值的场景,将需要更加复杂的代码处理。

[
  { label: '小红', value: '1' },
  { label: '小明', value: '2' },
  { label: '小芳', value: '3' }
]

组件设计(简易版本)

调用效果及代码

show1.png


<!--
 * @Date: 2020-12-09 17:52:54
 * @Author: surewinT 840325271@qq.com
 * @LastEditTime: 2022-05-09 14:22:01
 * @LastEditors: surewinT 840325271@qq.com
 * @Description: 调用页面
-->

<template>
    <div class="">
        <Test :checkboxList="checkboxList" v-model="result" />
    </div>
</template>

<script>
import Test from "./test.vue";
export default {
    components: {
        Test,
    },
    props: [],
    data() {
        return {
            checkboxList: [
                { label: "小红", value: "1" },
                { label: "小明", value: "2" },
                { label: "小芳", value: "3" },
            ],
            result: [],
        };
    },
    mounted() {},
    watch: {
        result() {
            console.log("变化了:", this.result);
        },
    },
    methods: {},
};
</script>

<style lang='scss' scoped>
</style>

改造后的组件(test.vue)

<!--
 * @Date: 2022-05-09 11:52:02
 * @Author: surewinT 840325271@qq.com
 * @LastEditTime: 2022-05-09 14:22:10
 * @LastEditors: surewinT 840325271@qq.com
 * @Description: 改造后的组件
-->

<template>
    <div class="">
        <el-checkbox-group v-model="labelResult">
            <el-checkbox v-for="(item, index) in labelList" :key="index" :label="item"> </el-checkbox>
        </el-checkbox-group>
    </div>
</template>

<script>
export default {
    components: {},
    props: {
        checkboxList: {
            type: Array,
            default: () => {
                return [];
            },
        },
    },
    data() {
        return {
            labelResult: [],
            labelList: [],
            labelMap: {},
        };
    },
    mounted() {
        this.loadData();
    },
    watch: {},
    methods: {
        // 初始化数据
        loadData() {
            this.checkboxList.forEach((res) => {
                this.labelList.push(res["label"]);
                this.labelMap[res["label"]] = res["value"];
            });
        },
    },
};
</script>

<style lang='scss' scoped>
</style>

组件设计(完整版)

组件简介

p-el-checkbox.png

调用效果及代码

show2.png


<!--
 * @Date: 2020-12-09 17:52:54
 * @Author: surewinT 840325271@qq.com
 * @LastEditTime: 2022-05-09 14:49:13
 * @LastEditors: surewinT 840325271@qq.com
 * @Description: 调用页面
-->

<template>
    <div class="">
        <p-el-checkbox
            v-model="result"
            resultType="Array"
            label="name"
            prop="id"
            :defaultCheck="defaultCheck"
            :checkboxList="checkboxList"
        />
    </div>
</template>

<script>
import Pelcheckbox from "./p-el-checkbox.vue";
export default {
    components: {
        "p-el-checkbox": Pelcheckbox,
    },
    props: [],
    data() {
        return {
            defaultCheck: ["1", "3"],
            checkboxList: [
                { name: "小红", id: "1" },
                { name: "小明", id: "2" },
                { name: "小芳", id: "3" },
            ],
            result: {},
        };
    },
    mounted() {},
    watch: {
        result: function () {
            console.log("变化了:", this.result);
        },
    },
    methods: {},
};
</script>

<style lang='scss' scoped>
</style>

组件源码(p-el-checkbox.vue)

<!--
 * @Author: surewinT 840325271@qq.com
 * @LastEditTime: 2022-05-09 14:57:09
 * @LastEditors: surewinT 840325271@qq.com
 * @Description: 改造 Element-UI 多选框组件 (el-checkbox)
-->

<template>
    <div :class="customClass">
        <el-checkbox
            v-if="showCheckAll"
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
        >
            全选
        </el-checkbox>
        <el-checkbox-group v-model="labelResult" :class="inline ? '' : 'al_checkbox'">
            <span v-for="(item, index) in labelList" :key="index">
                <el-checkbox :label="item" :class="labelClass" @change="handleCheckChange" v-if="judgeHidden(item)">
                    <span>
                        <slot
                            name="label"
                            :index="index"
                            :label="item"
                            :checkboxList="checkboxList"
                            :disabled="checkboxMap[item] && checkboxMap[item].disabled"
                            :data="checkboxList[index] ? JSON.parse(JSON.stringify(checkboxList[index])) : {}"
                        >
                            <span> {{ item }} </span>
                        </slot>
                    </span>
                </el-checkbox>
            </span>
        </el-checkbox-group>
    </div>
</template>

<script>
/**
 * @description:props说明
 * @param {Boolean} showCheckAll -是否显示全选按钮
 * @param {Boolean} inline -是否是行内表单
 * @param {Array<Object>} checkboxList -多选框组件的数据配置
 * @param {String} label -label对应的字段
 * @param {String} prop -value对应的字段
 * @param {Array} defaultCheck -默认勾选的项
 * @param {String} resultType -绑定值的类型(支持对象、数组两种格式)
 * @param {String} labelClass -单个选项绑定类名,可用于自定义样式
 * @param {String} customClass -多选框的绑定类型,可用于自定义样式
 * @param {Array} checkboxHidden -隐藏的表单项,元素对应checkboxList中prop的值
 */
export default {
    name: "p-el-checkbox",
    props: {
        showCheckAll: {
            type: Boolean,
            default: true,
        },
        inline: {
            type: Boolean,
            default: true,
        },
        checkboxList: {
            type: Array,
            default: () => {
                return [];
            },
        },
        label: {
            type: String,
            default: "label",
        },
        prop: {
            type: String,
            default: "value",
        },
        defaultCheck: {
            type: Array,
            default: () => {
                return [];
            },
        },
        resultType: {
            type: String,
            default: "Array", // 可选:Array 、Object
        },
        labelClass: {
            type: String,
            default: "",
        },
        customClass: {
            type: String,
            default: "",
        },
        checkboxHidden: {
            type: Array,
            default: function () {
                return [];
            },
        },
    },
    data() {
        return {
            labelList: [],
            labelResult: [],
            labelMap: {}, // label与res的映射(res指checkboxList每一项元素)
            isIndeterminate: false,
            checkAll: false,
            currentLabel: null,
            currentValue: null,
        };
    },
    mounted() {
        this.loadData();
    },
    computed: {
        arrayRusult: function () {
            let result = [];
            if (this.resultType == "Array") {
                this.labelResult.forEach((res) => {
                    result.push(this.labelMap[res]);
                });
            }
            return result;
        },
        objectRusult: function () {
            let obj = {};
            if (this.resultType == "Object") {
                for (let item in this.labelMap) {
                    if (this.checkboxHidden.indexOf(this.labelMap[item]) != -1) {
                        continue;
                    }
                    if (this.labelResult.indexOf(item) == -1) {
                        obj[this.labelMap[item]] = false;
                    } else {
                        obj[this.labelMap[item]] = true;
                    }
                }
            }
            return obj;
        },
        // 名字映射
        checkboxMap() {
            let obj = {};
            for (let res of this.checkboxList) {
                obj[res[this.label]] = res;
            }
            return obj;
        },
    },
    watch: {
        checkboxList() {
            this.loadData();
        },
        labelResult() {
            this.isIndeterminate = true;
            this.checkAll = false;
            if (this.labelResult.length == 0) {
                this.isIndeterminate = false;
                this.checkAll = false;
            } else if (this.labelResult.length == this.labelList.length - this.checkboxHidden.length) {
                this.isIndeterminate = false;
                this.checkAll = true;
            }
            // 返回数组结果
            if (this.resultType == "Array") {
                this.$emit("input", this.arrayRusult);
            }
            // 返回对象结果
            if (this.resultType == "Object") {
                this.$emit("input", this.objectRusult);
            }
        },
        defaultCheck() {
            this.labelResult = [];
            this.checkboxList.forEach((res) => {
                if (this.defaultCheck.indexOf(res[this.prop]) != -1) {
                    this.labelResult.push(res[this.label]);
                }
            });
        },
    },
    methods: {
        // 初始化数据
        loadData() {
            this.checkboxList.forEach((res) => {
                this.labelList.push(res[this.label]);
                this.labelMap[res[this.label]] = res[this.prop];
                if (this.defaultCheck.indexOf(res[this.prop]) != -1) {
                    this.labelResult.push(res[this.label]);
                }
            });
        },
        // 全选按钮
        handleCheckAllChange(val) {
            this.isIndeterminate = false;
            if (val) {
                this.isIndeterminate = false;
                this.checkAll = true;
                this.labelResult = JSON.parse(JSON.stringify(this.labelList));
                // 过滤隐藏选项
                this.labelResult = this.labelResult.filter((res) => {
                    let exist = this.checkboxHidden.indexOf(this.labelMap[res]);
                    return exist == -1;
                });
            } else {
                this.checkAll = false;
                this.labelResult = [];
            }
        },
        // 单击多选框
        handleCheckChange(val, e) {
            this.currentLabel = this.labelMap[e.target.value];
            this.currentValue = val;
            // 返回数组结果:(勾选结果,点击的prop,点击的prop是否勾选)
            if (this.resultType == "Array") {
                this.$emit("change", this.arrayRusult, this.currentLabel, this.currentValue);
            }
            // 返回对象结果:(勾选结果,点击的prop,点击的prop是否勾选)
            if (this.resultType == "Object") {
                this.$emit("change", this.objectRusult, this.currentLabel, this.currentValue);
            }
        },
        // 隐藏判断
        judgeHidden(name) {
            let show = this.checkboxHidden.indexOf(this.labelMap[name]) == -1 ? true : false;
            return show;
        },
    },
};
</script>

<style lang="scss" scoped>
.el-checkbox {
    display: inline-block;
    padding-right: 10px;
}
.al_checkbox {
    .el-checkbox {
        display: block;
        margin-right: 0;
    }
}
// 滚动条样式修改
::-webkit-scrollbar {
    width: 5px;
}
::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
    box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
    -webkit-border-radius: 10px;
    border-radius: 10px;
}
::-webkit-scrollbar-thumb {
    -webkit-border-radius: 10px;
    border-radius: 10px;
    background: rgba(155, 155, 155, 0.8);
    -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.2);
    box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.2);
}
::-webkit-scrollbar-thumb:window-inactive {
    background: rgba(155, 155, 155, 0.1);
}
</style>

仓库源码

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP