Checkbox.mjs 2.3 KB

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