mobile-picker.jsx 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { Picker as VanPicker, CheckboxGroup as VanCheckboxGroup, Checkbox as VanCheckbox, CellGroup as VanCellGroup, Cell as VanCell } from 'vant'
  2. import { computed, ref, onBeforeUpdate } from 'vue'
  3. import { useOptions } from '@cip/components/hooks/form-input'
  4. import { formInputProps } from '../../form-input-props'
  5. export default {
  6. props: { ...formInputProps, customFieldName: {}, columns: {} },
  7. emits: ['confirm', 'cancel'],
  8. setup (props, { emit }) {
  9. // 是否多选
  10. const multiple = computed(() => {
  11. return props.config?.multiple ?? false
  12. })
  13. const { options, getValue } = useOptions(props, multiple)
  14. const confirm = (value) => {
  15. if (multiple.value) {
  16. emit('confirm', checked.value)
  17. } else {
  18. if (props.customFieldName.children) {
  19. value = value[value.length - 1]
  20. }
  21. emit('confirm', value)
  22. }
  23. }
  24. const cancel = (val) => {
  25. if (multiple.value) {
  26. checked.value = getValue(props.modelValue)
  27. }
  28. emit('cancel', val)
  29. }
  30. // 多选
  31. console.log('init', getValue(props.modelValue), props.modelValue)
  32. const checked = ref(getValue(props.modelValue))
  33. const checkboxRefs = ref([])
  34. const toggle = (index) => {
  35. checkboxRefs.value[index]?.toggle()
  36. }
  37. onBeforeUpdate(() => {
  38. checkboxRefs.value = []
  39. })
  40. const Buttons = () =>
  41. <div class="van-picker__toolbar">
  42. <button type="button" class="van-picker__cancel" onclick={cancel}>取消</button>
  43. <div class="van-picker__title van-ellipsis">{props.config.label}</div>
  44. <button type="button" class="van-picker__confirm" onclick={confirm}>确认</button>
  45. </div>
  46. const CellSlot = (item, index) => <VanCell key={index}
  47. title={item[props.customFieldName.text] ?? item}
  48. onclick={toggle(index)}>
  49. {{
  50. 'right-icon': () => <VanCheckbox name={item?.value ?? item} ref={el => { checkboxRefs[index] = el }} />
  51. }}
  52. </VanCell>
  53. const CellSlots = () => options.value.map((v, idx) => CellSlot(v, idx))
  54. const Checkbox = () => <VanCheckboxGroup v-model={checked.value}>
  55. {Buttons()}
  56. <VanCellGroup inset>
  57. {CellSlots()}
  58. </VanCellGroup>
  59. </VanCheckboxGroup>
  60. // 单选
  61. const Picker = () => <VanPicker title={props.config.label}
  62. columns={props.columns}
  63. columns-field-names={props.customFieldName}
  64. onConfirm={confirm}
  65. onCancel={cancel} />
  66. return () => multiple.value ? Checkbox() : Picker()
  67. }
  68. }