Sfoglia il codice sorgente

perf: improve `autoSelect` of `ApiComponent` (#5936)

* fix: 修复autoSelect不生效的问题,props.valueField已经被omit了

* feat: ApiComponent autoSelect支持使用函数,可以满足灵活性要求更高的场景
ming4762 5 mesi fa
parent
commit
b5700bd0b1

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

@@ -151,7 +151,7 @@ function fetchApi(): Promise<Record<string, any>> {
 | options | 直接传入选项数据,也作为api返回空数据时的后备数据 | `OptionsItem[]` | - | - |
 | visibleEvent | 触发重新请求数据的事件名 | `string` | - | - |
 | loadingSlot | 目标组件的插槽名称,用来显示一个"加载中"的图标 | `string` | - | - |
-| autoSelect | 自动设置选项 | `'first' \| 'last' \| 'none'\| false` | `false` | >5.5.4 |
+| autoSelect | 自动设置选项 | `'first' \| 'last' \| 'one'\| (item: OptionsItem[]) => OptionsItem \| false` | `false` | >5.5.4 |
 
 #### autoSelect 自动设置选项
 
@@ -160,6 +160,7 @@ function fetchApi(): Promise<Record<string, any>> {
 - `first`:自动选择第一个选项
 - `last`:自动选择最后一个选项
 - `one`:有且仅有一个选项时,自动选择它
+- `函数`:自定义选择逻辑,函数的参数为options,返回值为选择的选项
 - false:不自动选择选项
 
 ### Methods

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

@@ -59,9 +59,15 @@ interface Props {
    * - `first`:自动选择第一个选项
    * - `last`:自动选择最后一个选项
    * - `one`: 当请求的结果只有一个选项时,自动选择该选项
+   * - 函数:自定义选择逻辑,函数的参数为请求的结果数组,返回值为选择的选项
    * - false:不自动选择(默认)
    */
-  autoSelect?: 'first' | 'last' | 'one' | false;
+  autoSelect?:
+    | 'first'
+    | 'last'
+    | 'one'
+    | ((item: OptionsItem[]) => OptionsItem)
+    | false;
 }
 
 defineOptions({ name: 'ApiComponent', inheritAttrs: false });
@@ -209,24 +215,28 @@ function emitChange() {
     unref(getOptions).length > 0
   ) {
     let firstOption;
-    switch (props.autoSelect) {
-      case 'first': {
-        firstOption = unref(getOptions)[0];
-        break;
-      }
-      case 'last': {
-        firstOption = unref(getOptions)[unref(getOptions).length - 1];
-        break;
-      }
-      case 'one': {
-        if (unref(getOptions).length === 1) {
+    if (isFunction(props.autoSelect)) {
+      firstOption = props.autoSelect(unref(getOptions));
+    } else {
+      switch (props.autoSelect) {
+        case 'first': {
           firstOption = unref(getOptions)[0];
+          break;
+        }
+        case 'last': {
+          firstOption = unref(getOptions)[unref(getOptions).length - 1];
+          break;
+        }
+        case 'one': {
+          if (unref(getOptions).length === 1) {
+            firstOption = unref(getOptions)[0];
+          }
+          break;
         }
-        break;
       }
     }
 
-    if (firstOption) modelValue.value = firstOption[props.valueField];
+    if (firstOption) modelValue.value = firstOption.value;
   }
   emit('optionsChange', unref(getOptions));
 }