Skip to content

Commit b5700bd

Browse files
authored
perf: improve autoSelect of ApiComponent (vbenjs#5936)
* fix: 修复autoSelect不生效的问题,props.valueField已经被omit了 * feat: ApiComponent autoSelect支持使用函数,可以满足灵活性要求更高的场景
1 parent a8c4786 commit b5700bd

File tree

2 files changed

+26
-15
lines changed

2 files changed

+26
-15
lines changed

docs/src/components/common-ui/vben-api-component.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ function fetchApi(): Promise<Record<string, any>> {
151151
| options | 直接传入选项数据,也作为api返回空数据时的后备数据 | `OptionsItem[]` | - | - |
152152
| visibleEvent | 触发重新请求数据的事件名 | `string` | - | - |
153153
| loadingSlot | 目标组件的插槽名称,用来显示一个"加载中"的图标 | `string` | - | - |
154-
| autoSelect | 自动设置选项 | `'first' \| 'last' \| 'none'\| false` | `false` | >5.5.4 |
154+
| autoSelect | 自动设置选项 | `'first' \| 'last' \| 'one'\| (item: OptionsItem[]) => OptionsItem \| false` | `false` | >5.5.4 |
155155

156156
#### autoSelect 自动设置选项
157157

@@ -160,6 +160,7 @@ function fetchApi(): Promise<Record<string, any>> {
160160
- `first`:自动选择第一个选项
161161
- `last`:自动选择最后一个选项
162162
- `one`:有且仅有一个选项时,自动选择它
163+
- `函数`:自定义选择逻辑,函数的参数为options,返回值为选择的选项
163164
- false:不自动选择选项
164165

165166
### Methods

packages/effects/common-ui/src/components/api-component/api-component.vue

+24-14
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,15 @@ interface Props {
5959
* - `first`:自动选择第一个选项
6060
* - `last`:自动选择最后一个选项
6161
* - `one`: 当请求的结果只有一个选项时,自动选择该选项
62+
* - 函数:自定义选择逻辑,函数的参数为请求的结果数组,返回值为选择的选项
6263
* - false:不自动选择(默认)
6364
*/
64-
autoSelect?: 'first' | 'last' | 'one' | false;
65+
autoSelect?:
66+
| 'first'
67+
| 'last'
68+
| 'one'
69+
| ((item: OptionsItem[]) => OptionsItem)
70+
| false;
6571
}
6672
6773
defineOptions({ name: 'ApiComponent', inheritAttrs: false });
@@ -209,24 +215,28 @@ function emitChange() {
209215
unref(getOptions).length > 0
210216
) {
211217
let firstOption;
212-
switch (props.autoSelect) {
213-
case 'first': {
214-
firstOption = unref(getOptions)[0];
215-
break;
216-
}
217-
case 'last': {
218-
firstOption = unref(getOptions)[unref(getOptions).length - 1];
219-
break;
220-
}
221-
case 'one': {
222-
if (unref(getOptions).length === 1) {
218+
if (isFunction(props.autoSelect)) {
219+
firstOption = props.autoSelect(unref(getOptions));
220+
} else {
221+
switch (props.autoSelect) {
222+
case 'first': {
223223
firstOption = unref(getOptions)[0];
224+
break;
225+
}
226+
case 'last': {
227+
firstOption = unref(getOptions)[unref(getOptions).length - 1];
228+
break;
229+
}
230+
case 'one': {
231+
if (unref(getOptions).length === 1) {
232+
firstOption = unref(getOptions)[0];
233+
}
234+
break;
224235
}
225-
break;
226236
}
227237
}
228238
229-
if (firstOption) modelValue.value = firstOption[props.valueField];
239+
if (firstOption) modelValue.value = firstOption.value;
230240
}
231241
emit('optionsChange', unref(getOptions));
232242
}

0 commit comments

Comments
 (0)