关于javascript:组件封装改造-ElementUI-多选框组件-elcheckbox

7次阅读

共计 11030 个字符,预计需要花费 28 分钟才能阅读完成。

el-checkbox 多选框组件

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

理论业务场景

在理论业务开发中,咱们更多遇到是如下数组对象的格局。
咱们须要额定将数组进行 label、value 的拆分能力应用 el-checkbox。
如果要实现勾选、全选、默认赋值的场景,将须要更加简单的代码解决。

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

组件设计 (繁难版本)

调用成果及代码


<!--
 * @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>

组件设计(完整版)

组件简介

调用成果及代码


<!--
 * @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: "ByCheckboxGroup",
    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>
正文完
 0