UNPKG

magiccube-vue3

Version:

vue3-js版组件库

86 lines (78 loc) 2.69 kB
import { computed } from 'vue' const Switch = { name: 'McSwitch', props: { modelValue: [Boolean, String, Number], activeText: String, inactiveText: String, activeColor: String, inactiveColor: String, activeValue: [String, Number], inactiveValue: [String, Number], disabled: Boolean }, emits: ['update:modelValue', 'change'], setup(props, { emit }) { const handleClick = () => { if(props.disabled) return false model.value = !model.value } const model = computed({ get() { if (typeof props.modelValue === 'boolean') { return props.modelValue } else if (typeof props.modelValue === 'string' || typeof props.modelValue === 'number') { return props.modelValue === props.activeValue } else { return false } }, set(value) { let _val if (props.activeValue && props.inactiveValue) { _val = value ? props.activeValue : props.inactiveValue } else { _val = value } emit('update:modelValue', _val) emit('change', _val) } }) const getStyle = () => { if (props.activeColor) { const color = model.value ? props.activeColor : props.inactiveColor return { background: color } } else { return {} } } return () => ( <div class={[ 'mc-switch', props.disabled? 'mc-switch__disabled' : '' ]} onClick={handleClick}> <div class="mc-switch__wrap"> {props.activeText ? <span class="mc-switch__label left">{props.activeText}</span> : ''} <span class={{ 'mc-switch__inner': true, active: model.value }} style={getStyle()}> <i class={{ 'mc-switch__dot': true, active: model.value }}></i> </span> {props.inactiveText ? <span class="mc-switch__label right">{props.inactiveText}</span> : ''} </div> </div> ) } } Switch.install = (app) => { app.component(Switch.name, Switch) } const McSwitch = Switch export { McSwitch, McSwitch as default }