ASelect.vue 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <script setup lang="ts">
  2. import { EpPropMergeType } from 'element-plus/es/utils'
  3. import { StrAnyObj, StrAnyObjArr } from '@/typings'
  4. import { FormOptionType } from '@/components/AForm/type'
  5. import { getAsyncResult, getResult } from '@/utils'
  6. import { getDictByCode } from '@/utils/dict'
  7. const props = withDefaults(
  8. defineProps<
  9. {
  10. modelValue: EpPropMergeType<
  11. (
  12. | BooleanConstructor
  13. | ObjectConstructor
  14. | ArrayConstructor
  15. | NumberConstructor
  16. | StringConstructor
  17. )[],
  18. unknown,
  19. unknown
  20. >
  21. style?: StrAnyObj
  22. placeholder?: string
  23. clearable?: boolean
  24. disabled?: boolean
  25. filterable?: boolean
  26. multiple?: boolean
  27. change?: (value: any) => void
  28. } & FormOptionType
  29. >(),
  30. {
  31. clearable: true,
  32. disabled: false,
  33. filterable: true,
  34. multiple: false,
  35. autoLoadOption: true,
  36. keyName: 'key',
  37. labelName: 'label',
  38. disabledName: 'disabled'
  39. }
  40. )
  41. const options = ref<StrAnyObjArr>([])
  42. const emits = defineEmits(['update:modelValue'])
  43. const computedModelValue = computed({
  44. get() {
  45. return props.modelValue
  46. },
  47. set(newValue) {
  48. emits('update:modelValue', newValue)
  49. }
  50. })
  51. defineExpose({ loadOption, reloadOption, clearOption })
  52. if (props.autoLoadOption) {
  53. loadOption()
  54. }
  55. function loadOption() {
  56. if (props.dict) {
  57. getDictByCode(props.dict).then((resp) => {
  58. options.value = resp
  59. })
  60. } else {
  61. getAsyncResult<StrAnyObjArr>(props.option, []).then((resp) => {
  62. options.value = resp
  63. })
  64. }
  65. }
  66. function reloadOption() {
  67. clearOption()
  68. loadOption()
  69. }
  70. function clearOption() {
  71. emits('update:modelValue', null)
  72. options.value = []
  73. }
  74. </script>
  75. <template>
  76. <el-select
  77. v-model="computedModelValue"
  78. :placeholder="placeholder"
  79. :clearable="clearable"
  80. :disabled="disabled"
  81. :style="style"
  82. :filterable="filterable"
  83. :multiple="multiple"
  84. style="width: 100%"
  85. @change="(value: any) => change?.(value)"
  86. >
  87. <el-option
  88. v-for="item in options"
  89. :key="item[props.dict ? 'value' : keyName]"
  90. :label="item[props.dict ? 'label' : labelName]"
  91. :value="item[props.dict ? 'value' : keyName]"
  92. :disabled="getResult(item[disabledName], false)"
  93. />
  94. </el-select>
  95. </template>