Checkbox.mjs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { watch, computed, defineComponent, mergeProps as _mergeProps, createVNode as _createVNode } from "vue";
  2. import { pick, extend, truthProp, createNamespace } from "../utils/index.mjs";
  3. import { CHECKBOX_GROUP_KEY } from "../checkbox-group/CheckboxGroup.mjs";
  4. import { useParent, useCustomFieldValue } from "@vant/use";
  5. import { useExpose } from "../composables/use-expose.mjs";
  6. import Checker, { checkerProps } from "./Checker.mjs";
  7. const [name, bem] = createNamespace("checkbox");
  8. const checkboxProps = extend({}, checkerProps, {
  9. shape: String,
  10. bindGroup: truthProp,
  11. indeterminate: {
  12. type: Boolean,
  13. default: null
  14. }
  15. });
  16. var stdin_default = defineComponent({
  17. name,
  18. props: checkboxProps,
  19. emits: ["change", "update:modelValue"],
  20. setup(props, {
  21. emit,
  22. slots
  23. }) {
  24. const {
  25. parent
  26. } = useParent(CHECKBOX_GROUP_KEY);
  27. const setParentValue = (checked2) => {
  28. const {
  29. name: name2
  30. } = props;
  31. const {
  32. max,
  33. modelValue
  34. } = parent.props;
  35. const value = modelValue.slice();
  36. if (checked2) {
  37. const overlimit = max && value.length >= +max;
  38. if (!overlimit && !value.includes(name2)) {
  39. value.push(name2);
  40. if (props.bindGroup) {
  41. parent.updateValue(value);
  42. }
  43. }
  44. } else {
  45. const index = value.indexOf(name2);
  46. if (index !== -1) {
  47. value.splice(index, 1);
  48. if (props.bindGroup) {
  49. parent.updateValue(value);
  50. }
  51. }
  52. }
  53. };
  54. const checked = computed(() => {
  55. if (parent && props.bindGroup) {
  56. return parent.props.modelValue.indexOf(props.name) !== -1;
  57. }
  58. return !!props.modelValue;
  59. });
  60. const toggle = (newValue = !checked.value) => {
  61. if (parent && props.bindGroup) {
  62. setParentValue(newValue);
  63. } else {
  64. emit("update:modelValue", newValue);
  65. }
  66. if (props.indeterminate !== null) emit("change", newValue);
  67. };
  68. watch(() => props.modelValue, (value) => {
  69. if (props.indeterminate === null) emit("change", value);
  70. });
  71. useExpose({
  72. toggle,
  73. props,
  74. checked
  75. });
  76. useCustomFieldValue(() => props.modelValue);
  77. return () => _createVNode(Checker, _mergeProps({
  78. "bem": bem,
  79. "role": "checkbox",
  80. "parent": parent,
  81. "checked": checked.value,
  82. "onToggle": toggle
  83. }, props), pick(slots, ["default", "icon"]));
  84. }
  85. });
  86. export {
  87. checkboxProps,
  88. stdin_default as default
  89. };