UNPKG

@ithinkdt/naive

Version:

iThinkDT Naive UI

126 lines (119 loc) 3.99 kB
import { computed, ref, watch, defineComponent } from 'vue' import { NCheckboxGroup, NCheckbox, NFlex } from 'ithinkdt-ui' import { useI18n } from '@ithinkdt/core' export const NCheckboxs = defineComponent({ name: 'NCheckboxs', inheritAttrs: false, props: { options: { type: Array, default: () => [], }, vertical: { type: Boolean, default: false, }, default: { type: [Boolean, String, Object], default: false, }, gap: { type: [Number, String, Array], default: undefined, }, value: { type: Array, default: undefined, }, labelPadding: { type: String, default: undefined, }, labelField: { type: String, default: 'label', }, valueField: { type: String, default: 'value', }, disabledField: { type: String, default: 'disabled', }, }, emits: { 'update:value': () => true, }, setup(props, { emit, attrs }) { const { t } = useI18n() const defaultLabel = computed(() => { if (!props.default) return '' if (props.default === true) return t('form.all') if (typeof props.default === 'string') return props.default return props.default?.[props.labelField] ?? t('form.all') }) const checked = ref([]) watch( () => props.value, (v) => (checked.value = v), { immediate: true }, ) const emitValue = (v) => { emit('update:value', v) } const onAll = () => { emitValue( checked.value?.length === props.options.length ? [] : props.options.map((it) => it[props.valueField]), ) } const indeterminate = computed(() => props.options.length > checked.value?.length && checked.value?.length > 0) const style = computed(() => { return { '--n-label-padding': props.labelPadding, } }) return () => { const group = ( <NCheckboxGroup {...attrs} value={checked.value} onUpdateValue={emitValue}> <NFlex size={props.gap ?? (props.vertical ? undefined : 'small')} vertical={props.vertical} style={!props.default && props.vertical ? { padding: '6px 0 0' } : {}} > {props.options?.map((op) => ( <NCheckbox value={op[props.valueField]} disabled={op[props.disabledField]} style={style.value} > {op[props.labelField]} </NCheckbox> ))} </NFlex> </NCheckboxGroup> ) return props.default ? ( <NFlex size={props.gap ?? (props.vertical ? undefined : 'small')} vertical={props.vertical} style={props.vertical ? { padding: '6px 0 0' } : {}} > <span> <NCheckbox indeterminate={indeterminate.value} checked={checked.value?.length > 0} onUpdateChecked={onAll} style={style.value} > {defaultLabel.value} </NCheckbox> </span> {group} </NFlex> ) : ( group ) } }, })