feat: 明细表中的下拉框支持label、value分开存储以提升首次渲染性能

This commit is contained in:
gaoyunqi
2024-05-20 15:25:38 +08:00
parent 386bba6e75
commit 78493e8f6d
3 changed files with 268 additions and 261 deletions

View File

@ -242,6 +242,7 @@ export const advanceComponents = [
responsive: false, responsive: false,
respNewRow: false, respNewRow: false,
placeholder: t('请选择下拉选择'), placeholder: t('请选择下拉选择'),
sepTextField: '',
showLabel: true, showLabel: true,
showSearch: false, showSearch: false,
clearable: false, clearable: false,

View File

@ -1,274 +1,280 @@
<template> <template>
<a-select <a-select v-model:value="selectedValue" :filter-option="handleFilterOption" :mode="mode" :options="getOptions" :placeholder="placeholder" allowClear v-bind="$attrs" @change="handleChange" @dropdown-visible-change="handleFetch">
@dropdown-visible-change="handleFetch" <template v-for="item in Object.keys($slots)" #[item]="data">
v-bind="$attrs" <slot :name="item" v-bind="data || {}"></slot>
@change="handleChange" </template>
:options="getOptions" <template v-if="loading" #suffixIcon>
v-model:value="selectedValue" <LoadingOutlined spin />
:placeholder="placeholder" </template>
:mode="mode" <template v-if="loading" #notFoundContent>
:filter-option="handleFilterOption" <span>
allowClear <LoadingOutlined class="mr-1" spin />
> {{ t('component.form.apiSelectNotFound') }}
<template #[item]="data" v-for="item in Object.keys($slots)"> </span>
<slot :name="item" v-bind="data || {}"></slot> </template>
</template> </a-select>
<template #suffixIcon v-if="loading">
<LoadingOutlined spin />
</template>
<template #notFoundContent v-if="loading">
<span>
<LoadingOutlined spin class="mr-1" />
{{ t('component.form.apiSelectNotFound') }}
</span>
</template>
</a-select>
</template> </template>
<script lang="ts"> <script lang="ts">
import { import { defineComponent, PropType, ref, computed, unref, watch, inject, onMounted, watchEffect } from 'vue';
defineComponent, import { isFunction } from '/@/utils/is';
PropType, import { useAttrs } from '/@/hooks/core/useAttrs';
ref, import { get, omit } from 'lodash-es';
computed, import { LoadingOutlined } from '@ant-design/icons-vue';
unref, import { useI18n } from '/@/hooks/web/useI18n';
watch, import { propTypes } from '/@/utils/propTypes';
inject, import { getDicDetailList } from '/@/api/system/dic';
onMounted, import { getDatasourceData } from '/@/api/system/datasource';
watchEffect, import { apiConfigFunc, camelCaseString, isValidJSON } from '/@/utils/event/design';
} from 'vue'; import {debounce} from 'lodash-es';
import { isFunction } from '/@/utils/is';
import { useAttrs } from '/@/hooks/core/useAttrs';
import { get, omit } from 'lodash-es';
import { LoadingOutlined } from '@ant-design/icons-vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { propTypes } from '/@/utils/propTypes';
import { getDicDetailList } from '/@/api/system/dic';
import { getDatasourceData } from '/@/api/system/datasource';
import { apiConfigFunc, camelCaseString, isValidJSON } from '/@/utils/event/design';
type OptionsItem = { label: string; value: string; disabled?: boolean }; type OptionsItem = { label: string; value: string; disabled?: boolean };
export default defineComponent({ export default defineComponent({
name: 'ApiSelect', name: 'ApiSelect',
components: { components: {
LoadingOutlined, LoadingOutlined
}, },
inheritAttrs: false, inheritAttrs: false,
props: { props: {
value: { value: {
type: [Array, Object, String, Number], type: [Array, Object, String, Number]
}, },
numberToString: propTypes.bool, numberToString: propTypes.bool,
api: { api: {
type: Function as PropType<(arg?: Recordable) => Promise<OptionsItem[]>>, type: Function as PropType<(arg?: Recordable) => Promise<OptionsItem[]>>,
default: null, default: null
}, },
// api params // api params
params: { params: {
type: [Array, Object, String, Number], type: [Array, Object, String, Number]
}, },
placeholder: String, placeholder: String,
resultField: propTypes.string.def(''), resultField: propTypes.string.def(''),
labelField: propTypes.string.def('label'), labelField: propTypes.string.def('label'),
valueField: propTypes.string.def('value'), valueField: propTypes.string.def('value'),
immediate: propTypes.bool.def(true), immediate: propTypes.bool.def(true),
alwaysLoad: propTypes.bool.def(false), alwaysLoad: propTypes.bool.def(false),
//数据来源 默认为空 如果不为空 则参数 api //数据来源 默认为空 如果不为空 则参数 api
datasourceType: String, datasourceType: String,
//静态数据默认选项 //静态数据默认选项
staticOptions: Array as PropType<OptionsItem[]>, staticOptions: Array as PropType<OptionsItem[]>,
apiConfig: Object, apiConfig: Object,
mode: String, mode: String,
mainKey: String, mainKey: String,
index: Number, index: Number,
}, sepTextField: String, // 独立存储文本部分
emits: ['options-change', 'change', 'update:value'], row: Object // 行数据,在明细表里生效
setup(props, { emit }) { },
const options = ref<OptionsItem[]>([]); emits: ['options-change', 'change', 'update:value'],
const loading = ref(false); setup(props, { emit }) {
const isFirstLoad = ref(true); const options = ref<OptionsItem[]>([]);
const emitData = ref<any[]>([]); const loading = ref(false);
const attrs = useAttrs(); const isFirstLoad = ref(true);
const { t } = useI18n(); const emitData = ref<any[]>([]);
const formModel = inject<any>('formModel', null); const attrs = useAttrs();
const isCamelCase = inject<boolean>('isCamelCase', false); const { t } = useI18n();
// Embedded in the form, just use the hook binding to perform form verification const formModel = inject<any>('formModel', null);
const selectedValue = ref<string | number | undefined>(undefined); const isCamelCase = inject<boolean>('isCamelCase', false);
// Embedded in the form, just use the hook binding to perform form verification
const selectedValue = ref<string | number | undefined>(undefined);
const valChanged = ref(false);
// label分开存储时第一次懒加载会同时处罚两次fetch所以这里延迟执行
const fetch = debounce(_fetch, 200, {leading: false, trailing: true});
const getOptions = computed(() => { const getOptions = computed(() => {
const { labelField, valueField, numberToString } = props; const { labelField, valueField, numberToString } = props;
if (Array.isArray(unref(options))) { if (Array.isArray(unref(options))) {
return unref(options).reduce((prev, next: Recordable) => { return unref(options).reduce((prev, next: Recordable) => {
if (next) { if (next) {
const value = next[valueField]; const value = next[valueField];
prev.push({ prev.push({
...omit(next, [labelField, valueField]), ...omit(next, [labelField, valueField]),
label: next[labelField], label: next[labelField],
value: numberToString ? `${value}` : value, value: numberToString ? `${value}` : value
}); });
} }
return prev; return prev;
}, [] as OptionsItem[]); }, [] as OptionsItem[]);
} else { } else {
return []; return [];
}
});
watchEffect(() => {
if (props.datasourceType === 'api' && props.apiConfig?.apiParams) {
props.apiConfig.apiParams.forEach((params) => {
params.tableInfo?.forEach((o) => {
if (o.bindType == 'data') {
let val = isValidJSON(o.value);
let field = '';
if (val && val.bindTable) {
let table = !isCamelCase
? val.bindTable + 'List'
: camelCaseString(val.bindTable + '_List');
field = !isCamelCase ? val.bindField : camelCaseString(val.bindField);
formModel &&
formModel[table!][props.index || 0] &&
formModel[table!][props.index || 0][field];
} else if (val && val.bindField) {
field = !isCamelCase ? val.bindField : camelCaseString(val.bindField);
formModel && formModel[field];
} }
}
}); });
});
fetch();
}
});
watch(
() => [props.params, props.apiConfig],
() => {
unref(isFirstLoad) && fetch();
},
{ deep: true },
);
watch( watchEffect(() => {
() => props.datasourceType, if (props.datasourceType === 'api' && props.apiConfig?.apiParams) {
(val) => { props.apiConfig.apiParams.forEach((params) => {
fetch(); params.tableInfo?.forEach((o) => {
selectedValue.value = if (o.bindType == 'data') {
!!props.value && val === 'staticData' ? (props.value as any) : undefined; let val = isValidJSON(o.value);
}, let field = '';
); if (val && val.bindTable) {
let table = !isCamelCase ? val.bindTable + 'List' : camelCaseString(val.bindTable + '_List');
field = !isCamelCase ? val.bindField : camelCaseString(val.bindField);
formModel && formModel[table!][props.index || 0] && formModel[table!][props.index || 0][field];
} else if (val && val.bindField) {
field = !isCamelCase ? val.bindField : camelCaseString(val.bindField);
formModel && formModel[field];
}
}
});
});
fetch();
}
});
watch( function setInitOptions() {
() => props.value, const { sepTextField, row } = props;
() => { if (sepTextField && row && row[sepTextField]) {
selectedValue.value = ((typeof props.value === 'string' && !!props.value const labelArr = row[sepTextField].split(',');
? props.value?.split(',') const idArr = (selectedValue.value + '').split(',');
: props.value) || undefined) as any; options.value = idArr.map((id, index) => {
}, return {
{ label: labelArr[index],
immediate: true, value: id
}, };
); });
onMounted(() => { }
fetch(); }
selectedValue.value = ((typeof props.value === 'string' && !!props.value
? props.value?.split(',')
: props.value) || undefined) as any;
});
async function fetch() { watch(
options.value = []; () => [props.params, props.apiConfig],
let api; () => {
if (props.datasourceType) { unref(isFirstLoad) && fetch();
if (props.datasourceType === 'staticData') { },
options.value = props.staticOptions!; { deep: true }
emitChange();
}
if (props.datasourceType === 'dic') {
api = getDicDetailList;
}
if (props.datasourceType === 'datasource') {
api = getDatasourceData;
}
if (props.datasourceType === 'api') {
options.value = await apiConfigFunc(
props.apiConfig,
isCamelCase,
formModel,
props.index,
); );
}
} else { watch(
api = props.api; () => props.datasourceType,
(val) => {
fetch();
selectedValue.value = !!props.value && val === 'staticData' ? (props.value as any) : undefined;
}
);
watch(
() => props.value,
() => {
selectedValue.value = ((typeof props.value === 'string' && !!props.value ? props.value?.split(',') : props.value) || undefined) as any;
},
{
immediate: true
}
);
function updateSepTextField(arr) {
if (!props.sepTextField || !props.row) {
return;
}
const options = unref(getOptions);
const txtArr = options
.filter((opt) => {
return arr.includes(opt.value);
})
.map((item) => item.label);
props.row[props.sepTextField] = txtArr.join(',');
}
onMounted(() => {
fetch();
selectedValue.value = ((typeof props.value === 'string' && !!props.value ? props.value?.split(',') : props.value) || undefined) as any;
});
async function _fetch() {
const { sepTextField } = props;
if (!valChanged.value && sepTextField) {
return setInitOptions();
}
options.value = [];
let api;
if (props.datasourceType) {
if (props.datasourceType === 'staticData') {
options.value = props.staticOptions!;
emitChange();
}
if (props.datasourceType === 'dic') {
api = getDicDetailList;
}
if (props.datasourceType === 'datasource') {
api = getDatasourceData;
}
if (props.datasourceType === 'api') {
options.value = await apiConfigFunc(props.apiConfig, isCamelCase, formModel, props.index);
}
} else {
api = props.api;
}
if (!api || !isFunction(api)) return;
options.value = [];
try {
if (!props.params) return;
loading.value = true;
const res = await api(props.params);
isFirstLoad.value = false;
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;
}
}
const handleFilterOption = (input: string, option) => {
const label = option.label || option.name;
return label.toLowerCase().includes(input.toLowerCase());
};
async function handleFetch(visible) {
if (visible) {
if (props.alwaysLoad) {
await fetch();
} else if (!props.immediate && unref(isFirstLoad)) {
await fetch();
isFirstLoad.value = false;
} else if (props.sepTextField && !valChanged.value) {
valChanged.value = true;
await fetch();
}
}
}
function emitChange() {
emit('options-change', unref(getOptions));
}
function handleChange(value, ...args) {
const val = Array.isArray(value) ? value.join(',') : value;
emitData.value = args;
emit('update:value', val);
emit('change', val);
selectedValue.value = props.value === undefined ? val : (((typeof props.value === 'string' && !!props.value ? props.value?.split(',') : props.value) || undefined) as any);
updateSepTextField(Array.isArray(value) ? value : [value]);
}
return {
selectedValue,
attrs,
getOptions,
loading,
t,
handleFetch,
handleChange,
handleFilterOption
};
} }
});
if (!api || !isFunction(api)) return;
options.value = [];
try {
if (!props.params) return;
loading.value = true;
const res = await api(props.params);
isFirstLoad.value = false;
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;
}
}
const handleFilterOption = (input: string, option) => {
const label = option.label || option.name;
return label.toLowerCase().includes(input.toLowerCase());
};
async function handleFetch(visible) {
if (visible) {
if (props.alwaysLoad) {
await fetch();
} else if (!props.immediate && unref(isFirstLoad)) {
await fetch();
isFirstLoad.value = false;
}
}
}
function emitChange() {
emit('options-change', unref(getOptions));
}
function handleChange(value, ...args) {
const val = Array.isArray(value) ? value.join(',') : value;
emitData.value = args;
emit('update:value', val);
emit('change', val);
selectedValue.value =
props.value === undefined
? val
: (((typeof props.value === 'string' && !!props.value
? props.value?.split(',')
: props.value) || undefined) as any);
}
return {
selectedValue,
attrs,
getOptions,
loading,
t,
handleFetch,
handleChange,
handleFilterOption,
};
},
});
</script> </script>

View File

@ -146,7 +146,7 @@ function schemeList(
if (isViewProcess) { if (isViewProcess) {
schema.dynamicDisabled = true; schema.dynamicDisabled = true;
} }
if ((permissionConfig.children || []).find((item) => item.fieldId === '_row_ctrl_' && !item.edit)) { if ((permissionConfig?.children || []).find((item) => item.fieldId === '_row_ctrl_' && !item.edit)) {
schema.componentProps.disableAddRow = true; schema.componentProps.disableAddRow = true;
} }
if (!permissionConfig?.view) { if (!permissionConfig?.view) {