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

This commit is contained in:
invalid w 2023-10-08 15:25:49 +08:00 committed by GitHub
parent f3f2f548e6
commit 1519f47f7d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

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