ApiComplete.vue 2.21 KB
<script setup lang="ts">
  import { AutoComplete } from 'ant-design-vue';
  import get from 'lodash-es/get';
  import omit from 'lodash-es/omit';
  import { computed, ref, unref, watch, watchEffect } from 'vue';
  import { isFunction } from '/@/utils/is';
  type OptionsItem = { text: string; value: string };

  const props = withDefaults(
    defineProps<{
      value?: string;
      api?: (arg?: Recordable) => Promise<OptionsItem[]>;
      onSearchQuery?: boolean;
      params?: Recordable;
      resultField?: string;
      valueField?: string;
      labelField?: string;
      immediate?: boolean;
    }>(),
    {
      valueField: 'value',
      labelField: 'label',
      immediate: true,
    }
  );

  const emit = defineEmits(['update:value', 'options-change']);

  const loading = ref(false);

  const isFirstLoad = ref(true);

  const options = ref<OptionsItem[]>([]);

  const getOptions = computed(() => {
    const { labelField, valueField } = props;

    return unref(options).reduce((prev, next: Recordable) => {
      if (next) {
        const value = next[valueField];
        prev.push({
          ...omit(next, [labelField, valueField]),
          text: next[labelField],
          value,
        });
      }
      return prev;
    }, [] as OptionsItem[]);
  });

  const fetch = async () => {
    const api = props.api;
    if (!api || !isFunction(api)) return;
    options.value = [];
    try {
      loading.value = true;
      const res = await api(props.params);
      if (Array.isArray(res)) {
        options.value = res;
        emitChange();
        return;
      }
      if (props.resultField) {
        options.value = get(res, props.resultField) || [];
      }
      emitChange();
    } catch (error) {
      console.warn(error);
    } finally {
      loading.value = false;
    }
  };

  function emitChange() {
    emit('options-change', unref(getOptions));
  }

  const handleChange = (value: any) => {
    emit('update:value', value);
  };

  watchEffect(() => {
    props.immediate && fetch();
  });

  watch(
    () => props.params,
    () => {
      !unref(isFirstLoad) && fetch();
    },
    { deep: true }
  );
</script>

<template>
  <AutoComplete :value="value" @change="handleChange" :options="getOptions" />
</template>