Switch.mjs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { defineComponent, createVNode as _createVNode } from "vue";
  2. import { addUnit, numericProp, unknownProp, createNamespace } from "../utils/index.mjs";
  3. import { useCustomFieldValue } from "@vant/use";
  4. import { Loading } from "../loading/index.mjs";
  5. const [name, bem] = createNamespace("switch");
  6. const switchProps = {
  7. size: numericProp,
  8. loading: Boolean,
  9. disabled: Boolean,
  10. modelValue: unknownProp,
  11. activeColor: String,
  12. inactiveColor: String,
  13. activeValue: {
  14. type: unknownProp,
  15. default: true
  16. },
  17. inactiveValue: {
  18. type: unknownProp,
  19. default: false
  20. }
  21. };
  22. var stdin_default = defineComponent({
  23. name,
  24. props: switchProps,
  25. emits: ["change", "update:modelValue"],
  26. setup(props, {
  27. emit,
  28. slots
  29. }) {
  30. const isChecked = () => props.modelValue === props.activeValue;
  31. const onClick = () => {
  32. if (!props.disabled && !props.loading) {
  33. const newValue = isChecked() ? props.inactiveValue : props.activeValue;
  34. emit("update:modelValue", newValue);
  35. emit("change", newValue);
  36. }
  37. };
  38. const renderLoading = () => {
  39. if (props.loading) {
  40. const color = isChecked() ? props.activeColor : props.inactiveColor;
  41. return _createVNode(Loading, {
  42. "class": bem("loading"),
  43. "color": color
  44. }, null);
  45. }
  46. if (slots.node) {
  47. return slots.node();
  48. }
  49. };
  50. useCustomFieldValue(() => props.modelValue);
  51. return () => {
  52. var _a;
  53. const {
  54. size,
  55. loading,
  56. disabled,
  57. activeColor,
  58. inactiveColor
  59. } = props;
  60. const checked = isChecked();
  61. const style = {
  62. fontSize: addUnit(size),
  63. backgroundColor: checked ? activeColor : inactiveColor
  64. };
  65. return _createVNode("div", {
  66. "role": "switch",
  67. "class": bem({
  68. on: checked,
  69. loading,
  70. disabled
  71. }),
  72. "style": style,
  73. "tabindex": disabled ? void 0 : 0,
  74. "aria-checked": checked,
  75. "onClick": onClick
  76. }, [_createVNode("div", {
  77. "class": bem("node")
  78. }, [renderLoading()]), (_a = slots.background) == null ? void 0 : _a.call(slots)]);
  79. };
  80. }
  81. });
  82. export {
  83. stdin_default as default,
  84. switchProps
  85. };