refactor: checkbox

refactor-checkbox
tangjinzhou 2021-12-28 16:41:58 +08:00
parent 4f3823eeda
commit 346393f81e
16 changed files with 334 additions and 274 deletions

View File

@ -1,36 +1,15 @@
import type { ExtractPropTypes } from 'vue'; import { watchEffect, onMounted, defineComponent, inject, onBeforeUnmount, ref } from 'vue';
import { defineComponent, inject, nextTick } from 'vue';
import PropTypes from '../_util/vue-types';
import classNames from '../_util/classNames'; import classNames from '../_util/classNames';
import VcCheckbox from '../vc-checkbox/Checkbox'; import VcCheckbox from '../vc-checkbox/Checkbox';
import hasProp, { getOptionProps, getSlot } from '../_util/props-util'; import { flattenChildren } from '../_util/props-util';
import { defaultConfigProvider } from '../config-provider';
import warning from '../_util/warning'; import warning from '../_util/warning';
import type { RadioChangeEvent } from '../radio/interface'; import type { RadioChangeEvent } from '../radio/interface';
import type { EventHandler } from '../_util/EventInterface'; import type { EventHandler } from '../_util/EventInterface';
import { useInjectFormItemContext } from '../form/FormItemContext'; import { useInjectFormItemContext } from '../form/FormItemContext';
function noop() {} import useConfigInject from '../_util/hooks/useConfigInject';
export const checkboxProps = () => { import type { CheckboxProps } from './interface';
return { import { CheckboxGroupContextKey, checkboxProps } from './interface';
prefixCls: PropTypes.string,
defaultChecked: PropTypes.looseBool,
checked: PropTypes.looseBool,
disabled: PropTypes.looseBool,
isGroup: PropTypes.looseBool,
value: PropTypes.any,
name: PropTypes.string,
id: PropTypes.string,
indeterminate: PropTypes.looseBool,
type: PropTypes.string.def('checkbox'),
autofocus: PropTypes.looseBool,
onChange: PropTypes.func,
'onUpdate:checked': PropTypes.func,
skipGroup: PropTypes.looseBool,
};
};
export type CheckboxProps = Partial<ExtractPropTypes<ReturnType<typeof checkboxProps>>>;
export default defineComponent({ export default defineComponent({
name: 'ACheckbox', name: 'ACheckbox',
@ -38,113 +17,79 @@ export default defineComponent({
__ANT_CHECKBOX: true, __ANT_CHECKBOX: true,
props: checkboxProps(), props: checkboxProps(),
emits: ['change', 'update:checked'], emits: ['change', 'update:checked'],
setup() { setup(props, { emit, attrs, slots, expose }) {
const formItemContext = useInjectFormItemContext(); const formItemContext = useInjectFormItemContext();
return { const { prefixCls, direction } = useConfigInject('checkbox', props);
formItemContext, const checkboxGroup = inject(CheckboxGroupContextKey, undefined);
configProvider: inject('configProvider', defaultConfigProvider), const uniId = Symbol('checkboxUniId');
checkboxGroupContext: inject('checkboxGroupContext', undefined),
};
},
watch: { watchEffect(() => {
value(value, prevValue) { if (!props.skipGroup && checkboxGroup) {
if (this.skipGroup) { checkboxGroup.registerValue(uniId, props.value);
return;
}
nextTick(() => {
const { checkboxGroupContext: checkboxGroup = {} } = this;
if (checkboxGroup.registerValue && checkboxGroup.cancelValue) {
checkboxGroup.cancelValue(prevValue);
checkboxGroup.registerValue(value);
} }
}); });
}, onBeforeUnmount(() => {
}, if (checkboxGroup) {
checkboxGroup.cancelValue(uniId);
mounted() {
const { value, checkboxGroupContext: checkboxGroup = {} } = this;
if (checkboxGroup.registerValue) {
checkboxGroup.registerValue(value);
} }
});
onMounted(() => {
warning( warning(
hasProp(this, 'checked') || this.checkboxGroupContext || !hasProp(this, 'value'), props.checked !== undefined || checkboxGroup || props.value === undefined,
'Checkbox', 'Checkbox',
'`value` is not validate prop, do you mean `checked`?', '`value` is not validate prop, do you mean `checked`?',
); );
}, });
beforeUnmount() {
const { value, checkboxGroupContext: checkboxGroup = {} } = this;
if (checkboxGroup.cancelValue) {
checkboxGroup.cancelValue(value);
}
},
methods: {
handleChange(event: RadioChangeEvent) {
const targetChecked = event.target.checked;
this.$emit('update:checked', targetChecked);
// this.$emit('input', targetChecked);
this.$emit('change', event);
},
focus() {
(this.$refs.vcCheckbox as HTMLInputElement).focus();
},
blur() {
(this.$refs.vcCheckbox as HTMLInputElement).blur();
},
},
render() { const handleChange = (event: RadioChangeEvent) => {
const props = getOptionProps(this); const targetChecked = event.target.checked;
const { checkboxGroupContext: checkboxGroup, $attrs } = this; emit('update:checked', targetChecked);
const children = getSlot(this); emit('change', event);
const { };
indeterminate, const checkboxRef = ref();
prefixCls: customizePrefixCls, const focus = () => {
skipGroup, checkboxRef.value?.focus();
id = this.formItemContext.id.value, };
...restProps const blur = () => {
} = props; checkboxRef.value?.blur();
const getPrefixCls = this.configProvider.getPrefixCls; };
const prefixCls = getPrefixCls('checkbox', customizePrefixCls); expose({
const { focus,
onMouseenter = noop, blur,
onMouseleave = noop, });
onInput, return () => {
class: className, const children = flattenChildren(slots.default?.());
style, const { indeterminate, skipGroup, id = formItemContext.id.value, ...restProps } = props;
...restAttrs const { onMouseenter, onMouseleave, onInput, class: className, style, ...restAttrs } = attrs;
} = $attrs; const checkboxProps: CheckboxProps = {
const checkboxProps: any = {
...restProps, ...restProps,
id, id,
prefixCls, prefixCls: prefixCls.value,
...restAttrs, ...restAttrs,
}; };
if (checkboxGroup && !skipGroup) { if (checkboxGroup && !skipGroup) {
checkboxProps.onChange = (...args) => { checkboxProps.onChange = (...args) => {
this.$emit('change', ...args); emit('change', ...args);
this.formItemContext.onFieldChange();
checkboxGroup.toggleOption({ label: children, value: props.value }); checkboxGroup.toggleOption({ label: children, value: props.value });
}; };
checkboxProps.name = checkboxGroup.name; checkboxProps.name = checkboxGroup.name.value;
checkboxProps.checked = checkboxGroup.sValue.indexOf(props.value) !== -1; checkboxProps.checked = checkboxGroup.mergedValue.value.indexOf(props.value) !== -1;
checkboxProps.disabled = props.disabled || checkboxGroup.disabled; checkboxProps.disabled = props.disabled || checkboxGroup.disabled.value;
checkboxProps.indeterminate = indeterminate; checkboxProps.indeterminate = indeterminate;
} else { } else {
checkboxProps.onChange = this.handleChange; checkboxProps.onChange = handleChange;
} }
const classString = classNames( const classString = classNames(
{ {
[`${prefixCls}-wrapper`]: true, [`${prefixCls.value}-wrapper`]: true,
[`${prefixCls}-wrapper-checked`]: checkboxProps.checked, [`${prefixCls.value}-rtl`]: direction.value === 'rtl',
[`${prefixCls}-wrapper-disabled`]: checkboxProps.disabled, [`${prefixCls.value}-wrapper-checked`]: checkboxProps.checked,
[`${prefixCls.value}-wrapper-disabled`]: checkboxProps.disabled,
}, },
className, className,
); );
const checkboxClass = classNames({ const checkboxClass = classNames({
[`${prefixCls}-indeterminate`]: indeterminate, [`${prefixCls.value}-indeterminate`]: indeterminate,
}); });
return ( return (
<label <label
@ -153,9 +98,10 @@ export default defineComponent({
onMouseenter={onMouseenter as EventHandler} onMouseenter={onMouseenter as EventHandler}
onMouseleave={onMouseleave as EventHandler} onMouseleave={onMouseleave as EventHandler}
> >
<VcCheckbox {...checkboxProps} class={checkboxClass} ref="vcCheckbox" /> <VcCheckbox {...checkboxProps} class={checkboxClass} ref={checkboxRef} />
{children.length ? <span>{children}</span> : null} {children.length ? <span>{children}</span> : null}
</label> </label>
); );
};
}, },
}); });

View File

@ -1,134 +1,116 @@
import type { PropType } from 'vue'; import { computed, ref, watch, defineComponent, provide } from 'vue';
import { defineComponent, inject, provide } from 'vue';
import PropTypes from '../_util/vue-types';
import Checkbox from './Checkbox'; import Checkbox from './Checkbox';
import hasProp, { getSlot } from '../_util/props-util';
import { defaultConfigProvider } from '../config-provider';
import type { VueNode } from '../_util/type';
import { useInjectFormItemContext } from '../form/FormItemContext'; import { useInjectFormItemContext } from '../form/FormItemContext';
import useConfigInject from '../_util/hooks/useConfigInject';
import type { CheckboxOptionType } from './interface';
import { CheckboxGroupContextKey, checkboxGroupProps } from './interface';
export type CheckboxValueType = string | number | boolean;
export interface CheckboxOptionType {
label: VueNode;
value: CheckboxValueType;
disabled?: boolean;
indeterminate?: boolean;
onChange?: (e: Event) => void;
}
function noop() {}
export default defineComponent({ export default defineComponent({
name: 'ACheckboxGroup', name: 'ACheckboxGroup',
props: { props: checkboxGroupProps(),
name: PropTypes.string,
prefixCls: PropTypes.string,
defaultValue: { type: Array as PropType<Array<CheckboxValueType>> },
value: { type: Array as PropType<Array<CheckboxValueType>> },
options: { type: Array as PropType<Array<CheckboxOptionType | string>> },
disabled: PropTypes.looseBool,
onChange: PropTypes.func,
id: PropTypes.string,
},
emits: ['change', 'update:value'], emits: ['change', 'update:value'],
setup() { setup(props, { slots, emit, expose }) {
const formItemContext = useInjectFormItemContext(); const formItemContext = useInjectFormItemContext();
return { const { prefixCls, direction } = useConfigInject('checkbox', props);
formItemContext, const mergedValue = ref((props.value === undefined ? props.defaultValue : props.value) || []);
configProvider: inject('configProvider', defaultConfigProvider), watch(
}; () => props.value,
() => {
mergedValue.value = props.value || [];
}, },
);
data() { const options = computed(() => {
const { value, defaultValue } = this; return props.options.map(option => {
return {
sValue: value || defaultValue || [],
registeredValues: [],
};
},
watch: {
value(val) {
this.sValue = val || [];
},
},
created() {
provide('checkboxGroupContext', this);
},
methods: {
getOptions() {
const { options = [], $slots } = this;
return options.map(option => {
if (typeof option === 'string') { if (typeof option === 'string') {
return { return {
label: option, label: option,
value: option, value: option,
}; };
} }
let label = option.label; return option;
if (label === undefined && $slots.label) {
label = $slots.label(option);
}
return { ...option, label };
}); });
}, });
cancelValue(value: CheckboxValueType) { const triggerUpdate = ref(Symbol());
this.registeredValues = this.registeredValues.filter(val => val !== value); const registeredValuesMap = ref<Map<Symbol, string>>(new Map());
}, const cancelValue = (id: Symbol) => {
registeredValuesMap.value.delete(id);
triggerUpdate.value = Symbol();
};
const registerValue = (id: Symbol, value: string) => {
registeredValuesMap.value.set(id, value);
triggerUpdate.value = Symbol();
};
registerValue(value: CheckboxValueType) { const registeredValues = ref(new Map());
this.registeredValues = [...this.registeredValues, value]; watch(triggerUpdate, () => {
}, const valuseMap = new Map();
toggleOption(option: CheckboxOptionType) { for (const value of registeredValuesMap.value.values()) {
const { registeredValues } = this; valuseMap.set(value, true);
const optionIndex = this.sValue.indexOf(option.value); }
const value = [...this.sValue]; registeredValues.value = valuseMap;
});
const toggleOption = (option: CheckboxOptionType) => {
const optionIndex = mergedValue.value.indexOf(option.value);
const value = [...mergedValue.value];
if (optionIndex === -1) { if (optionIndex === -1) {
value.push(option.value); value.push(option.value);
} else { } else {
value.splice(optionIndex, 1); value.splice(optionIndex, 1);
} }
if (!hasProp(this, 'value')) { if (props.value === undefined) {
this.sValue = value; mergedValue.value = value;
} }
const options = this.getOptions();
const val = value const val = value
.filter(val => registeredValues.indexOf(val) !== -1) .filter(val => registeredValues.value.has(val))
.sort((a, b) => { .sort((a, b) => {
const indexA = options.findIndex(opt => opt.value === a); const indexA = options.value.findIndex(opt => opt.value === a);
const indexB = options.findIndex(opt => opt.value === b); const indexB = options.value.findIndex(opt => opt.value === b);
return indexA - indexB; return indexA - indexB;
}); });
// this.$emit('input', val); emit('update:value', val);
this.$emit('update:value', val); emit('change', val);
this.$emit('change', val); formItemContext.onFieldChange();
this.formItemContext.onFieldChange(); };
}, provide(CheckboxGroupContextKey, {
}, cancelValue,
render() { registerValue,
const { $props: props, $data: state } = this; toggleOption,
const { prefixCls: customizePrefixCls, options, id = this.formItemContext.id.value } = props; mergedValue,
const getPrefixCls = this.configProvider.getPrefixCls; name: computed(() => props.name),
const prefixCls = getPrefixCls('checkbox', customizePrefixCls); disabled: computed(() => props.disabled),
let children = getSlot(this); });
const groupPrefixCls = `${prefixCls}-group`; expose({
if (options && options.length > 0) { mergedValue,
children = this.getOptions().map(option => ( });
return () => {
const { id = formItemContext.id.value } = props;
let children = null;
const groupPrefixCls = `${prefixCls.value}-group`;
if (options.value && options.value.length > 0) {
children = options.value.map(option => (
<Checkbox <Checkbox
prefixCls={prefixCls} prefixCls={prefixCls.value}
key={option.value.toString()} key={option.value.toString()}
disabled={'disabled' in option ? option.disabled : props.disabled} disabled={'disabled' in option ? option.disabled : props.disabled}
indeterminate={option.indeterminate} indeterminate={option.indeterminate}
value={option.value} value={option.value}
checked={state.sValue.indexOf(option.value) !== -1} checked={mergedValue.value.indexOf(option.value) !== -1}
onChange={option.onChange || noop} onChange={option.onChange}
class={`${groupPrefixCls}-item`} class={`${groupPrefixCls}-item`}
> >
{option.label} {option.label === undefined ? slots.label?.(option) : option.label}
</Checkbox> </Checkbox>
)); ));
} }
return ( return (
<div class={groupPrefixCls} id={id}> <div
{children} class={[groupPrefixCls, { [`${groupPrefixCls}-rtl`]: direction.value === 'rtl' }]}
id={id}
>
{children || slots.default?.()}
</div> </div>
); );
};
}, },
}); });

View File

@ -3,8 +3,10 @@
exports[`renders ./components/checkbox/demo/basic.vue correctly 1`] = `<label class="ant-checkbox-wrapper"><span class="ant-checkbox"><input type="checkbox" class="ant-checkbox-input"><span class="ant-checkbox-inner"></span></span><span>Checkbox</span></label>`; exports[`renders ./components/checkbox/demo/basic.vue correctly 1`] = `<label class="ant-checkbox-wrapper"><span class="ant-checkbox"><input type="checkbox" class="ant-checkbox-input"><span class="ant-checkbox-inner"></span></span><span>Checkbox</span></label>`;
exports[`renders ./components/checkbox/demo/check-all.vue correctly 1`] = ` exports[`renders ./components/checkbox/demo/check-all.vue correctly 1`] = `
<div style="border-bottom: 1px solid #E9E9E9;"><label class="ant-checkbox-wrapper"><span class="ant-checkbox ant-checkbox-indeterminate"><input type="checkbox" class="ant-checkbox-input"><span class="ant-checkbox-inner"></span></span><span> Check all </span></label></div> <div><label class="ant-checkbox-wrapper"><span class="ant-checkbox ant-checkbox-indeterminate"><input type="checkbox" class="ant-checkbox-input"><span class="ant-checkbox-inner"></span></span><span> Check all </span></label></div>
<br> <div class="ant-divider ant-divider-horizontal" role="separator">
<!---->
</div>
<div class="ant-checkbox-group"><label class="ant-checkbox-wrapper ant-checkbox-wrapper-checked ant-checkbox-group-item"><span class="ant-checkbox ant-checkbox-checked"><input type="checkbox" class="ant-checkbox-input" value="Apple"><span class="ant-checkbox-inner"></span></span><span>Apple</span></label><label class="ant-checkbox-wrapper ant-checkbox-group-item"><span class="ant-checkbox"><input type="checkbox" class="ant-checkbox-input" value="Pear"><span class="ant-checkbox-inner"></span></span><span>Pear</span></label><label class="ant-checkbox-wrapper ant-checkbox-wrapper-checked ant-checkbox-group-item"><span class="ant-checkbox ant-checkbox-checked"><input type="checkbox" class="ant-checkbox-input" value="Orange"><span class="ant-checkbox-inner"></span></span><span>Orange</span></label></div> <div class="ant-checkbox-group"><label class="ant-checkbox-wrapper ant-checkbox-wrapper-checked ant-checkbox-group-item"><span class="ant-checkbox ant-checkbox-checked"><input type="checkbox" class="ant-checkbox-input" value="Apple"><span class="ant-checkbox-inner"></span></span><span>Apple</span></label><label class="ant-checkbox-wrapper ant-checkbox-group-item"><span class="ant-checkbox"><input type="checkbox" class="ant-checkbox-input" value="Pear"><span class="ant-checkbox-inner"></span></span><span>Pear</span></label><label class="ant-checkbox-wrapper ant-checkbox-wrapper-checked ant-checkbox-group-item"><span class="ant-checkbox ant-checkbox-checked"><input type="checkbox" class="ant-checkbox-input" value="Orange"><span class="ant-checkbox-inner"></span></span><span>Orange</span></label></div>
`; `;
@ -22,7 +24,7 @@ exports[`renders ./components/checkbox/demo/disabled.vue correctly 1`] = `
<!----> <!---->
</label> </label>
<br> <br>
<label class="ant-checkbox-wrapper ant-checkbox-wrapper-disabled"><span class="ant-checkbox ant-checkbox-disabled"><input type="checkbox" disabled="" class="ant-checkbox-input"><span class="ant-checkbox-inner"></span></span> <label class="ant-checkbox-wrapper ant-checkbox-wrapper-checked ant-checkbox-wrapper-disabled"><span class="ant-checkbox ant-checkbox-checked ant-checkbox-disabled"><input type="checkbox" disabled="" class="ant-checkbox-input"><span class="ant-checkbox-inner"></span></span>
<!----> <!---->
</label> </label>
`; `;
@ -30,15 +32,18 @@ exports[`renders ./components/checkbox/demo/disabled.vue correctly 1`] = `
exports[`renders ./components/checkbox/demo/group.vue correctly 1`] = ` exports[`renders ./components/checkbox/demo/group.vue correctly 1`] = `
<div class="ant-checkbox-group"><label class="ant-checkbox-wrapper ant-checkbox-group-item"><span class="ant-checkbox"><input name="checkboxgroup" type="checkbox" class="ant-checkbox-input" value="Apple"><span class="ant-checkbox-inner"></span></span><span>Apple</span></label><label class="ant-checkbox-wrapper ant-checkbox-group-item"><span class="ant-checkbox"><input name="checkboxgroup" type="checkbox" class="ant-checkbox-input" value="Pear"><span class="ant-checkbox-inner"></span></span><span>Pear</span></label><label class="ant-checkbox-wrapper ant-checkbox-group-item"><span class="ant-checkbox"><input name="checkboxgroup" type="checkbox" class="ant-checkbox-input" value="Orange"><span class="ant-checkbox-inner"></span></span><span>Orange</span></label></div> <div class="ant-checkbox-group"><label class="ant-checkbox-wrapper ant-checkbox-group-item"><span class="ant-checkbox"><input name="checkboxgroup" type="checkbox" class="ant-checkbox-input" value="Apple"><span class="ant-checkbox-inner"></span></span><span>Apple</span></label><label class="ant-checkbox-wrapper ant-checkbox-group-item"><span class="ant-checkbox"><input name="checkboxgroup" type="checkbox" class="ant-checkbox-input" value="Pear"><span class="ant-checkbox-inner"></span></span><span>Pear</span></label><label class="ant-checkbox-wrapper ant-checkbox-group-item"><span class="ant-checkbox"><input name="checkboxgroup" type="checkbox" class="ant-checkbox-input" value="Orange"><span class="ant-checkbox-inner"></span></span><span>Orange</span></label></div>
<br> <br>
<br>
<div class="ant-checkbox-group"><label class="ant-checkbox-wrapper ant-checkbox-wrapper-checked ant-checkbox-group-item"><span class="ant-checkbox ant-checkbox-checked"><input type="checkbox" class="ant-checkbox-input" value="Apple"><span class="ant-checkbox-inner"></span></span><span>Apple</span></label><label class="ant-checkbox-wrapper ant-checkbox-group-item"><span class="ant-checkbox"><input type="checkbox" class="ant-checkbox-input" value="Pear"><span class="ant-checkbox-inner"></span></span><span>Pear</span></label><label class="ant-checkbox-wrapper ant-checkbox-group-item"><span class="ant-checkbox"><input type="checkbox" class="ant-checkbox-input" value="Orange"><span class="ant-checkbox-inner"></span></span><span>Orange</span></label></div> <div class="ant-checkbox-group"><label class="ant-checkbox-wrapper ant-checkbox-wrapper-checked ant-checkbox-group-item"><span class="ant-checkbox ant-checkbox-checked"><input type="checkbox" class="ant-checkbox-input" value="Apple"><span class="ant-checkbox-inner"></span></span><span>Apple</span></label><label class="ant-checkbox-wrapper ant-checkbox-group-item"><span class="ant-checkbox"><input type="checkbox" class="ant-checkbox-input" value="Pear"><span class="ant-checkbox-inner"></span></span><span>Pear</span></label><label class="ant-checkbox-wrapper ant-checkbox-group-item"><span class="ant-checkbox"><input type="checkbox" class="ant-checkbox-input" value="Orange"><span class="ant-checkbox-inner"></span></span><span>Orange</span></label></div>
<br> <br>
<br>
<div class="ant-checkbox-group"><label class="ant-checkbox-wrapper ant-checkbox-group-item"><span class="ant-checkbox"><input type="checkbox" class="ant-checkbox-input" value="Apple"><span class="ant-checkbox-inner"></span></span><span>Apple</span></label><label class="ant-checkbox-wrapper ant-checkbox-wrapper-checked ant-checkbox-group-item"><span class="ant-checkbox ant-checkbox-checked"><input type="checkbox" class="ant-checkbox-input" value="Pear"><span class="ant-checkbox-inner"></span></span><span>Pear</span></label><label class="ant-checkbox-wrapper ant-checkbox-group-item"><span class="ant-checkbox"><input type="checkbox" class="ant-checkbox-input" value="Orange"><span class="ant-checkbox-inner"></span></span><span>Orange</span></label></div> <div class="ant-checkbox-group"><label class="ant-checkbox-wrapper ant-checkbox-group-item"><span class="ant-checkbox"><input type="checkbox" class="ant-checkbox-input" value="Apple"><span class="ant-checkbox-inner"></span></span><span>Apple</span></label><label class="ant-checkbox-wrapper ant-checkbox-wrapper-checked ant-checkbox-group-item"><span class="ant-checkbox ant-checkbox-checked"><input type="checkbox" class="ant-checkbox-input" value="Pear"><span class="ant-checkbox-inner"></span></span><span>Pear</span></label><label class="ant-checkbox-wrapper ant-checkbox-group-item"><span class="ant-checkbox"><input type="checkbox" class="ant-checkbox-input" value="Orange"><span class="ant-checkbox-inner"></span></span><span>Orange</span></label></div>
<br> <br>
<br>
<div class="ant-checkbox-group"><label class="ant-checkbox-wrapper ant-checkbox-wrapper-checked ant-checkbox-wrapper-disabled ant-checkbox-group-item"><span class="ant-checkbox ant-checkbox-checked ant-checkbox-disabled"><input type="checkbox" disabled="" class="ant-checkbox-input" value="Apple"><span class="ant-checkbox-inner"></span></span><span><span style="color: red;">Apple</span></span></label><label class="ant-checkbox-wrapper ant-checkbox-wrapper-disabled ant-checkbox-group-item"><span class="ant-checkbox ant-checkbox-disabled"><input type="checkbox" disabled="" class="ant-checkbox-input" value="Pear"><span class="ant-checkbox-inner"></span></span><span>Pear</span></label><label class="ant-checkbox-wrapper ant-checkbox-wrapper-disabled ant-checkbox-group-item"><span class="ant-checkbox ant-checkbox-disabled"><input type="checkbox" disabled="" class="ant-checkbox-input" value="Orange"><span class="ant-checkbox-inner"></span></span><span>Orange</span></label></div> <div class="ant-checkbox-group"><label class="ant-checkbox-wrapper ant-checkbox-wrapper-checked ant-checkbox-wrapper-disabled ant-checkbox-group-item"><span class="ant-checkbox ant-checkbox-checked ant-checkbox-disabled"><input type="checkbox" disabled="" class="ant-checkbox-input" value="Apple"><span class="ant-checkbox-inner"></span></span><span><span style="color: red;">Apple</span></span></label><label class="ant-checkbox-wrapper ant-checkbox-wrapper-disabled ant-checkbox-group-item"><span class="ant-checkbox ant-checkbox-disabled"><input type="checkbox" disabled="" class="ant-checkbox-input" value="Pear"><span class="ant-checkbox-inner"></span></span><span>Pear</span></label><label class="ant-checkbox-wrapper ant-checkbox-wrapper-disabled ant-checkbox-group-item"><span class="ant-checkbox ant-checkbox-disabled"><input type="checkbox" disabled="" class="ant-checkbox-input" value="Orange"><span class="ant-checkbox-inner"></span></span><span>Orange</span></label></div>
`; `;
exports[`renders ./components/checkbox/demo/layout.vue correctly 1`] = ` exports[`renders ./components/checkbox/demo/layout.vue correctly 1`] = `
<div class="ant-checkbox-group"> <div class="ant-checkbox-group" style="width: 100%;">
<div class="ant-row"> <div class="ant-row">
<div class="ant-col ant-col-8"><label class="ant-checkbox-wrapper"><span class="ant-checkbox"><input type="checkbox" class="ant-checkbox-input" value="A"><span class="ant-checkbox-inner"></span></span><span>A</span></label></div> <div class="ant-col ant-col-8"><label class="ant-checkbox-wrapper"><span class="ant-checkbox"><input type="checkbox" class="ant-checkbox-input" value="A"><span class="ant-checkbox-inner"></span></span><span>A</span></label></div>
<div class="ant-col ant-col-8"><label class="ant-checkbox-wrapper"><span class="ant-checkbox"><input type="checkbox" class="ant-checkbox-input" value="B"><span class="ant-checkbox-inner"></span></span><span>B</span></label></div> <div class="ant-col ant-col-8"><label class="ant-checkbox-wrapper"><span class="ant-checkbox"><input type="checkbox" class="ant-checkbox-input" value="B"><span class="ant-checkbox-inner"></span></span><span>B</span></label></div>

View File

@ -103,11 +103,10 @@ describe('CheckboxGroup', () => {
props: { options }, props: { options },
sync: false, sync: false,
}); });
expect(wrapper.vm.mergedValue).toEqual([]);
expect(wrapper.vm.sValue).toEqual([]);
wrapper.setProps({ value: ['Apple'] }); wrapper.setProps({ value: ['Apple'] });
await asyncExpect(() => { await asyncExpect(() => {
expect(wrapper.vm.sValue).toEqual(['Apple']); expect(wrapper.vm.mergedValue).toEqual(['Apple']);
}); });
}); });

View File

@ -17,7 +17,7 @@ The `indeterminate` property can help you to achieve a 'check all' effect.
</docs> </docs>
<template> <template>
<div :style="{ borderBottom: '1px solid #E9E9E9' }"> <div>
<a-checkbox <a-checkbox
v-model:checked="checkAll" v-model:checked="checkAll"
:indeterminate="indeterminate" :indeterminate="indeterminate"
@ -26,7 +26,7 @@ The `indeterminate` property can help you to achieve a 'check all' effect.
Check all Check all
</a-checkbox> </a-checkbox>
</div> </div>
<br /> <a-divider />
<a-checkbox-group v-model:value="checkedList" :options="plainOptions" /> <a-checkbox-group v-model:value="checkedList" :options="plainOptions" />
</template> </template>
<script lang="ts"> <script lang="ts">

View File

@ -19,10 +19,13 @@ Generate a group of checkboxes from an array
<template> <template>
<a-checkbox-group v-model:value="value1" name="checkboxgroup" :options="plainOptions" /> <a-checkbox-group v-model:value="value1" name="checkboxgroup" :options="plainOptions" />
<br /> <br />
<br />
<a-checkbox-group v-model:value="value2" :options="plainOptions" /> <a-checkbox-group v-model:value="value2" :options="plainOptions" />
<br /> <br />
<br />
<a-checkbox-group v-model:value="value3" :options="options" /> <a-checkbox-group v-model:value="value3" :options="options" />
<br /> <br />
<br />
<a-checkbox-group v-model:value="value4" :options="optionsWithDisabled" disabled> <a-checkbox-group v-model:value="value4" :options="optionsWithDisabled" disabled>
<template #label="{ value }"> <template #label="{ value }">
<span style="color: red">{{ value }}</span> <span style="color: red">{{ value }}</span>
@ -51,7 +54,6 @@ export default defineComponent({
value3: ['Pear'], value3: ['Pear'],
value4: ['Apple'], value4: ['Apple'],
}); });
return { return {
plainOptions, plainOptions,
options, options,

View File

@ -17,7 +17,7 @@ We can use Checkbox and Grid Checkbox.group, to implement complex layout
</docs> </docs>
<template> <template>
<a-checkbox-group v-model:value="value"> <a-checkbox-group v-model:value="value" style="width: 100%">
<a-row> <a-row>
<a-col :span="8"> <a-col :span="8">
<a-checkbox value="A">A</a-checkbox> <a-checkbox value="A">A</a-checkbox>
@ -41,8 +41,9 @@ We can use Checkbox and Grid Checkbox.group, to implement complex layout
import { defineComponent, ref } from 'vue'; import { defineComponent, ref } from 'vue';
export default defineComponent({ export default defineComponent({
setup() { setup() {
const value = ref([]);
return { return {
value: ref([]), value,
}; };
}, },
}); });

View File

@ -1,7 +1,8 @@
import type { App, Plugin } from 'vue'; import type { App, Plugin } from 'vue';
import Checkbox, { checkboxProps } from './Checkbox'; import Checkbox from './Checkbox';
import CheckboxGroup from './Group'; import CheckboxGroup from './Group';
export type { CheckboxProps } from './Checkbox'; export type { CheckboxProps, CheckboxGroupProps, CheckboxOptionType } from './interface';
export { checkboxProps, checkboxGroupProps } from './interface';
Checkbox.Group = CheckboxGroup; Checkbox.Group = CheckboxGroup;
@ -11,7 +12,7 @@ Checkbox.install = function (app: App) {
app.component(CheckboxGroup.name, CheckboxGroup); app.component(CheckboxGroup.name, CheckboxGroup);
return app; return app;
}; };
export { CheckboxGroup, checkboxProps }; export { CheckboxGroup };
export default Checkbox as typeof Checkbox & export default Checkbox as typeof Checkbox &
Plugin & { Plugin & {
readonly Group: typeof CheckboxGroup; readonly Group: typeof CheckboxGroup;

View File

@ -0,0 +1,78 @@
import type { ExtractPropTypes, InjectionKey, PropType, Ref } from 'vue';
import type { VueNode } from '../_util/type';
import PropTypes from '../_util/vue-types';
export type CheckboxValueType = string | number | boolean;
export interface CheckboxOptionType {
label?: VueNode;
value: CheckboxValueType;
disabled?: boolean;
indeterminate?: boolean;
onChange?: (e: Event) => void;
}
export const abstractCheckboxGroupProps = () => {
return {
name: String,
prefixCls: String,
options: {
type: Array as PropType<Array<CheckboxOptionType | string>>,
default: () => [] as Array<CheckboxOptionType | string>,
},
disabled: Boolean,
id: String,
};
};
export const checkboxGroupProps = () => {
return {
...abstractCheckboxGroupProps(),
defaultValue: { type: Array as PropType<Array<CheckboxValueType>> },
value: { type: Array as PropType<Array<CheckboxValueType>> },
onChange: { type: Function as PropType<(checkedValue: Array<CheckboxValueType>) => void> },
'onUpdate:value': {
type: Function as PropType<(checkedValue: Array<CheckboxValueType>) => void>,
},
};
};
export type CheckboxGroupProps = Partial<ExtractPropTypes<ReturnType<typeof checkboxGroupProps>>>;
export const abstractCheckboxProps = () => {
return {
prefixCls: String,
defaultChecked: { type: Boolean, default: undefined },
checked: { type: Boolean, default: undefined },
disabled: { type: Boolean, default: undefined },
isGroup: { type: Boolean, default: undefined },
value: PropTypes.any,
name: String,
id: String,
indeterminate: { type: Boolean, default: undefined },
type: { type: String, default: 'checkbox' },
autofocus: { type: Boolean, default: undefined },
onChange: PropTypes.func,
'onUpdate:checked': PropTypes.func,
skipGroup: { type: Boolean, default: false },
};
};
export const checkboxProps = () => {
return {
...abstractCheckboxProps(),
indeterminate: { type: Boolean, default: false },
};
};
export type CheckboxProps = Partial<ExtractPropTypes<ReturnType<typeof checkboxProps>>>;
export type CheckboxGroupContext = {
cancelValue: (id: Symbol) => void;
registerValue: (id: Symbol, value: string) => void;
toggleOption: (option: CheckboxOptionType) => void;
name: Ref<string>;
disabled: Ref<boolean>;
mergedValue: Ref<CheckboxValueType[]>;
};
export const CheckboxGroupContextKey: InjectionKey<CheckboxGroupContext> =
Symbol('CheckboxGroupContext');

View File

@ -2,3 +2,5 @@
@import './mixin'; @import './mixin';
.antCheckboxFn(); .antCheckboxFn();
@import './rtl';

View File

@ -7,11 +7,9 @@
.reset-component(); .reset-component();
position: relative; position: relative;
top: -0.09em; top: 0.2em;
display: inline-block;
line-height: 1; line-height: 1;
white-space: nowrap; white-space: nowrap;
vertical-align: middle;
outline: none; outline: none;
cursor: pointer; cursor: pointer;
@ -28,7 +26,7 @@
width: 100%; width: 100%;
height: 100%; height: 100%;
border: 1px solid @checkbox-color; border: 1px solid @checkbox-color;
border-radius: @border-radius-sm; border-radius: @border-radius-base;
visibility: hidden; visibility: hidden;
animation: antCheckboxEffect 0.36s ease-in-out; animation: antCheckboxEffect 0.36s ease-in-out;
animation-fill-mode: backwards; animation-fill-mode: backwards;
@ -47,9 +45,10 @@
display: block; display: block;
width: @checkbox-size; width: @checkbox-size;
height: @checkbox-size; height: @checkbox-size;
direction: ltr;
background-color: @checkbox-check-bg; background-color: @checkbox-check-bg;
border: @checkbox-border-width @border-style-base @border-color-base; border: @checkbox-border-width @border-style-base @border-color-base;
border-radius: @border-radius-sm; border-radius: @checkbox-border-radius;
// Fix IE checked style // Fix IE checked style
// https://github.com/ant-design/ant-design/issues/12597 // https://github.com/ant-design/ant-design/issues/12597
border-collapse: separate; border-collapse: separate;
@ -61,6 +60,8 @@
position: absolute; position: absolute;
top: 50%; top: 50%;
// https://github.com/ant-design/ant-design/pull/19452
// https://github.com/ant-design/ant-design/pull/31726
left: 21.5%; left: 21.5%;
display: table; display: table;
width: @check-width; width: @check-width;
@ -126,6 +127,7 @@
.@{checkbox-inner-prefix-cls} { .@{checkbox-inner-prefix-cls} {
background-color: @input-disabled-bg; background-color: @input-disabled-bg;
border-color: @border-color-base !important; border-color: @border-color-base !important;
&::after { &::after {
border-color: @input-disabled-bg; border-color: @input-disabled-bg;
border-collapse: separate; border-collapse: separate;
@ -147,13 +149,22 @@
.@{checkbox-prefix-cls}-wrapper { .@{checkbox-prefix-cls}-wrapper {
.reset-component(); .reset-component();
display: inline-flex;
display: inline-block; align-items: baseline;
line-height: unset; line-height: unset;
cursor: pointer; cursor: pointer;
&::after {
display: inline-block;
width: 0;
overflow: hidden;
content: '\a0';
}
&.@{checkbox-prefix-cls}-wrapper-disabled { &.@{checkbox-prefix-cls}-wrapper-disabled {
cursor: not-allowed; cursor: not-allowed;
} }
& + & { & + & {
margin-left: 8px; margin-left: 8px;
} }
@ -166,15 +177,16 @@
.@{checkbox-prefix-cls}-group { .@{checkbox-prefix-cls}-group {
.reset-component(); .reset-component();
display: inline-block;
display: inline-block;
&-item { &-item {
display: inline-block; margin-right: @checkbox-group-item-margin-right;
margin-right: 8px;
&:last-child { &:last-child {
margin-right: 0; margin-right: 0;
} }
} }
&-item + &-item { &-item + &-item {
margin-left: 0; margin-left: 0;
} }
@ -183,7 +195,7 @@
// 半选状态 // 半选状态
.@{checkbox-prefix-cls}-indeterminate { .@{checkbox-prefix-cls}-indeterminate {
.@{checkbox-inner-prefix-cls} { .@{checkbox-inner-prefix-cls} {
background-color: @component-background; background-color: @checkbox-check-bg;
border-color: @border-color-base; border-color: @border-color-base;
} }
.@{checkbox-inner-prefix-cls}::after { .@{checkbox-inner-prefix-cls}::after {
@ -213,6 +225,7 @@
transform: scale(1); transform: scale(1);
opacity: 0.5; opacity: 0.5;
} }
100% { 100% {
transform: scale(1.6); transform: scale(1.6);
opacity: 0; opacity: 0;

View File

@ -0,0 +1,28 @@
@import '../../style/mixins/index';
.antCheckboxFn(@checkbox-prefix-cls: ~'@{ant-prefix}-checkbox') {
.@{checkbox-prefix-cls}-rtl {
direction: rtl;
}
.@{checkbox-prefix-cls}-group {
&-item {
.@{checkbox-prefix-cls}-group-rtl & {
margin-right: 0;
margin-left: @checkbox-group-item-margin-right;
}
&:last-child {
.@{checkbox-prefix-cls}-group-rtl & {
margin-left: 0 !important;
}
}
}
&-item + &-item {
.@{checkbox-prefix-cls}-group-rtl & {
margin-left: @checkbox-group-item-margin-right;
}
}
}
}

View File

@ -40,6 +40,7 @@ export { default as Carousel } from './carousel';
export type { CascaderProps } from './cascader'; export type { CascaderProps } from './cascader';
export { default as Cascader } from './cascader'; export { default as Cascader } from './cascader';
export type { CheckboxProps, CheckboxGroupProps, CheckboxOptionType } from './checkbox';
export { default as Checkbox, CheckboxGroup } from './checkbox'; export { default as Checkbox, CheckboxGroup } from './checkbox';
export type { ColProps } from './col'; export type { ColProps } from './col';

View File

@ -241,6 +241,8 @@
@checkbox-check-color: #fff; @checkbox-check-color: #fff;
@checkbox-check-bg: @checkbox-check-color; @checkbox-check-bg: @checkbox-check-color;
@checkbox-border-width: @border-width-base; @checkbox-border-width: @border-width-base;
@checkbox-border-radius: @border-radius-base;
@checkbox-group-item-margin-right: 8px;
// Descriptions // Descriptions
@descriptions-bg: #fafafa; @descriptions-bg: #fafafa;

View File

@ -27,7 +27,7 @@ export default defineComponent({
type: 'checkbox', type: 'checkbox',
defaultChecked: false, defaultChecked: false,
}), }),
emits: ['click', 'focus', 'blur', 'change', 'keydown', 'keypress', 'keyup'], emits: ['click', 'change'],
setup(props, { attrs, emit, expose }) { setup(props, { attrs, emit, expose }) {
const checked = ref(props.checked === undefined ? props.defaultChecked : props.checked); const checked = ref(props.checked === undefined ? props.defaultChecked : props.checked);
const inputRef = ref<HTMLInputElement>(); const inputRef = ref<HTMLInputElement>();