index.tsx 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { use } from '../utils';
  2. import Loading from '../loading';
  3. import { switchProps, SharedSwitchProps } from './shared';
  4. import { emit, inherit } from '../utils/functional';
  5. // Types
  6. import { CreateElement, RenderContext } from 'vue/types';
  7. import { DefaultSlots } from '../utils/use/sfc';
  8. export type SwitchEvents = {
  9. onChange?(checked: boolean): void;
  10. };
  11. const [sfc, bem] = use('switch');
  12. function Switch(
  13. h: CreateElement,
  14. props: SharedSwitchProps,
  15. slots: DefaultSlots,
  16. ctx: RenderContext<SharedSwitchProps>
  17. ) {
  18. const { value, loading, disabled, activeValue, inactiveValue } = props;
  19. const style = {
  20. fontSize: props.size,
  21. backgroundColor: value ? props.activeColor : props.inactiveColor
  22. };
  23. const onClick = () => {
  24. if (!disabled && !loading) {
  25. const newValue = value === activeValue ? inactiveValue : activeValue;
  26. emit(ctx, 'input', newValue);
  27. emit(ctx, 'change', newValue);
  28. }
  29. };
  30. return (
  31. <div
  32. class={bem({
  33. on: value === activeValue,
  34. disabled
  35. })}
  36. style={style}
  37. onClick={onClick}
  38. {...inherit(ctx)}
  39. >
  40. <div class={bem('node')}>
  41. {loading && <Loading class={bem('loading')} />}
  42. </div>
  43. </div>
  44. );
  45. }
  46. Switch.props = switchProps;
  47. export default sfc<SharedSwitchProps, SwitchEvents>(Switch);