Switch.mjs 2.2 KB

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