elementui-Checkbox-使用el-checkbox仿写el-radio

1,445 阅读1分钟

Checkbox-使用el-checkbox仿写el-radio

问题描述

image.png

  1. 产品觉得el-radio样式太丑了,喜欢el-checkbox打钩的

展示效果

image.png

  1. 实现切换选中,可以只保留一个选中,也可以一个也不保留

展示代码

<template>
    <div>
        <el-checkbox-group v-model="groupList" @change="(val)=>{checkBoxHandle1(val,'groupList','selectValue')}">
            <el-checkbox :key="key" v-for="(item,key) in selectList" :label="item.value">{{item.label}}
            </el-checkbox>
        </el-checkbox-group>
        <el-button @click="lookValueHandle">打印值</el-button>
    </div>
</template>

<script>
export default {
    data () {
        return {
            selectList: [
                {
                    value: 1,
                    label: '合格'
                },
                {
                    value: 2,
                    label: '不合格'
                }
            ],
            groupList: [], // 初始化回显值
            selectValue: null, // 当前选中值
        }
    },
    created () {
        this.initSelectHandle()
    },
    methods: {
        // 初始化选中值
        initSelectHandle () {
            this.selectValue = 1
            this.groupList = [].concat(this.selectValue)
        },
        // 切换选中: 可以取消选中自身
        checkBoxHandle1 (val, hxList, needValue) {
            if (val.length === 0) {
                this[needValue] = null
                return
            }
            if (val.length === 1) {
                this[needValue] = this[hxList][0]
                return
            }
            this[hxList] = val.filter(v => v !== this[needValue])
            this[needValue] = this[hxList][0]
        },
        // 切换选中: 不可以取消选中自身
        checkBoxHandle2 (val, hxList, needValue) {
            if (val.length === 0) {
                this[hxList] = [].concat(this[needValue])
                return
            }
            if (val.length === 1) {
                this[needValue] = this[hxList][0]
                return
            }
            this[hxList] = val.filter(v => v !== this[needValue])
            this[needValue] = this[hxList][0]
        },
        // 打印值
        lookValueHandle () {
            console.log('selectValue', this.selectValue)
        }
    },
}
</script>

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