Explorar o código

fix(ApiSelect): 移除watchEffect引发的重复请求 (#3107)

invalid w hai 1 ano
pai
achega
1519f47f7d
Modificáronse 1 ficheiros con 9 adicións e 12 borrados
  1. 9 12
      src/components/Form/src/components/ApiSelect.vue

+ 9 - 12
src/components/Form/src/components/ApiSelect.vue

@@ -21,7 +21,7 @@
   </Select>
 </template>
 <script lang="ts">
-  import { defineComponent, PropType, ref, watchEffect, computed, unref, watch } from 'vue';
+  import { defineComponent, PropType, ref, computed, unref, watch } from 'vue';
   import { Select } from 'ant-design-vue';
   import { isFunction } from '/@/utils/is';
   import { useRuleFormItem } from '/@/hooks/component/useFormItem';
@@ -61,7 +61,8 @@
     setup(props, { emit }) {
       const options = ref<OptionsItem[]>([]);
       const loading = ref(false);
-      const isFirstLoad = ref(true);
+      // 首次是否加载过了
+      const isFirstLoaded = ref(false);
       const emitData = ref<any[]>([]);
       const attrs = useAttrs();
       const { t } = useI18n();
@@ -86,10 +87,6 @@
         return data.length > 0 ? data : props.options;
       });
 
-      watchEffect(() => {
-        props.immediate && !props.alwaysLoad && fetch();
-      });
-
       watch(
         () => state.value,
         (v) => {
@@ -100,18 +97,19 @@
       watch(
         () => props.params,
         () => {
-          !unref(isFirstLoad) && fetch();
+          !unref(isFirstLoaded) && fetch();
         },
-        { deep: true },
+        { deep: true, immediate: props.immediate },
       );
 
       async function fetch() {
         const api = props.api;
-        if (!api || !isFunction(api)) return;
+        if (!api || !isFunction(api) || loading.value) return;
         options.value = [];
         try {
           loading.value = true;
           const res = await api(props.params);
+          isFirstLoaded.value = true;
           if (Array.isArray(res)) {
             options.value = res;
             emitChange();
@@ -128,13 +126,12 @@
         }
       }
 
-      async function handleFetch(visible) {
+      async function handleFetch(visible: boolean) {
         if (visible) {
           if (props.alwaysLoad) {
             await fetch();
-          } else if (!props.immediate && unref(isFirstLoad)) {
+          } else if (!props.immediate && !unref(isFirstLoaded)) {
             await fetch();
-            isFirstLoad.value = false;
           }
         }
       }