# 16. ApiSelect API选择器
URL: /%E6%96%87%E6%A1%A3/04.%E5%BC%80%E5%8F%91%E6%96%87%E6%A1%A3/01.%20%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91/03.%20%E7%BB%84%E4%BB%B6%E5%BA%93%E6%96%87%E6%A1%A3/07.%20%E9%80%89%E6%8B%A9%E5%99%A8%E7%BB%84%E4%BB%B6/16.%20ApiSelect%20API%E9%80%89%E6%8B%A9%E5%99%A8

ApiSelect API 下拉选择组件使用指南


# ApiSelect API 选择器

> [!info] 通过 API 动态加载选项数据的下拉选择器，支持远程搜索、懒加载等功能。

## 基本用法

```vue
<template>
  <ApiSelect
    v-model:value="deptId"
    :api="getDeptList"
    label-field="deptName"
    value-field="id"
    placeholder="请选择部门"
  />
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { defHttp } from '@/utils/http/axios';

const deptId = ref('');

// API 函数
async function getDeptList() {
  return await defHttp.get({ url: '/system/depart/list' });
}
</script>
```

## Props 属性

| 属性 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| value | `string \| number \| array` | - | 选中值 |
| api | `function` | - | 获取选项数据的 API 函数（必填） |
| labelField | `string` | `'label'` | 作为标签的字段名 |
| valueField | `string` | `'value'` | 作为值的字段名 |
| numberToString | `boolean` | - | 数字转字符串 |
| resultField | `string` | `''` | 结果字段路径 |
| immediate | `boolean` | `true` | 是否立即加载数据 |
| params | `object` | `{}` | 请求参数 |

## Emits 事件

| 事件名 | 参数 | 说明 |
|--------|------|------|
| options-change | `options: array` | 选项变化时触发 |
| change | `value: any` | 值变化时触发 |

## API 函数定义

API 函数需要返回符合 Ant Design Vue Select options 格式的数据：

```typescript
// 方式一：直接返回 options 格式
async function getDeptList() {
  const result = await defHttp.get({ url: '/system/depart/list' });
  return result.map((item) => ({
    label: item.deptName,
    value: item.id,
  }));
}

// 方式二：使用 labelField 和 valueField 自动转换
async function getDeptList() {
  return await defHttp.get({ url: '/system/depart/list' });
}

// 方式三：返回嵌套结构
async function getDeptTree() {
  const result = await defHttp.get({ url: '/system/depart/tree' });
  return result.records;  // 使用 resultField 指定路径
}
```

## 在 BasicForm 中使用

```vue
<template>
  <BasicForm @register="registerForm" />
</template>

<script setup lang="ts">
import { useForm } from '@/components/Form';
import { defHttp } from '@/utils/http/axios';

// 部门列表 API
async function getDeptList() {
  return await defHttp.get({ url: '/system/depart/list' });
}

// 角色列表 API
async function getRoleList(params) {
  return await defHttp.get({ url: '/system/role/list', params });
}

const [registerForm] = useForm({
  schemas: [
    {
      field: 'deptId',
      label: '部门',
      component: 'ApiSelect',
      componentProps: {
        api: getDeptList,
        labelField: 'deptName',
        valueField: 'id',
        placeholder: '请选择部门',
      },
    },
    {
      field: 'roleId',
      label: '角色',
      component: 'ApiSelect',
      componentProps: {
        api: getRoleList,
        labelField: 'roleName',
        valueField: 'id',
        params: { status: 1 },  // 传递固定参数
      },
    },
  ],
});
</script>
```

## 带参数的请求

```vue
<template>
  <ApiSelect
    v-model:value="userId"
    :api="getUserList"
    :params="{ deptId: currentDeptId }"
    label-field="realname"
    value-field="id"
  />
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { defHttp } from '@/utils/http/axios';

const currentDeptId = ref('dept001');

async function getUserList(params) {
  return await defHttp.get({
    url: '/system/user/list',
    params: { deptId: params.deptId },
  });
}
</script>
```

## 结果字段路径

当 API 返回嵌套结构时，使用 `resultField` 指定数据路径：

```vue
<template>
  <ApiSelect
    v-model:value="userId"
    :api="getUserList"
    result-field="result.records"
    label-field="realname"
    value-field="id"
  />
</template>

<script setup lang="ts">
import { defHttp } from '@/utils/http/axios';

async function getUserList() {
  return await defHttp.get({
    url: '/system/user/page',
    params: { page: 1, size: 100 },
  });
  // 返回结构：{ success: true, result: { records: [...], total: 100 } }
}
</script>
```

## 禁用立即加载

```vue
<ApiSelect
  v-model:value="userId"
  :api="getUserList"
  :immediate="false"
  label-field="realname"
  value-field="id"
/>
<!-- 不会在组件挂载时自动请求数据 -->
```

## 混合静态选项

```vue
<template>
  <ApiSelect
    v-model:value="category"
    :api="getCategoryList"
    :options="[{ label: '全部', value: '' }]"
    label-field="name"
    value-field="id"
  />
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { defHttp } from '@/utils/http/axios';

const category = ref('');

async function getCategoryList() {
  return await defHttp.get({ url: '/product/category/list' });
}
// 最终选项：[{ label: '全部', value: '' }, ...动态加载的选项]
</script>
```

## 树形选择 (ApiTreeSelect)

```vue
<template>
  <ApiTreeSelect
    v-model:value="deptId"
    :api="getDeptTree"
    label-field="deptName"
    value-field="id"
    placeholder="请选择部门"
  />
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { defHttp } from '@/utils/http/axios';

const deptId = ref('');

async function getDeptTree() {
  return await defHttp.get({ url: '/system/depart/tree' });
}
</script>
```

## 远程搜索

```vue
<template>
  <ApiSelect
    v-model:value="keyword"
    :api="searchProducts"
    label-field="name"
    value-field="id"
    show-search
    :filter-option="false"
    @search="handleSearch"
  />
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { defHttp } from '@/utils/http/axios';

const keyword = ref('');
const searchParams = ref({ keyword: '' });

async function searchProducts() {
  return await defHttp.get({
    url: '/product/search',
    params: searchParams.value,
  });
}

function handleSearch(value) {
  searchParams.value.keyword = value;
}
</script>
```

## 完整示例

```vue
<template>
  <BasicForm @register="registerForm" />
</template>

<script setup lang="ts">
import { useForm } from '@/components/Form';
import { defHttp } from '@/utils/http/axios';

// 获取部门列表
async function getDeptList() {
  const result = await defHttp.get({ url: '/system/depart/list' });
  return result || [];
}

// 获取角色列表
async function getRoleList() {
  const result = await defHttp.get({ url: '/system/role/list' });
  return result || [];
}

// 获取用户列表（带参数）
async function getUserList(params) {
  const result = await defHttp.get({
    url: '/system/user/list',
    params: { ...params, status: 1 },
  });
  return result || [];
}

const [registerForm] = useForm({
  schemas: [
    {
      field: 'deptId',
      label: '所属部门',
      component: 'ApiSelect',
      componentProps: {
        api: getDeptList,
        labelField: 'deptName',
        valueField: 'id',
        placeholder: '请选择部门',
      },
    },
    {
      field: 'roleIds',
      label: '角色',
      component: 'ApiSelect',
      componentProps: {
        api: getRoleList,
        labelField: 'roleName',
        valueField: 'id',
        mode: 'multiple',
        placeholder: '请选择角色',
      },
    },
    {
      field: 'leaderId',
      label: '直属上级',
      component: 'ApiSelect',
      componentProps: ({ schema }) => ({
        api: getUserList,
        labelField: 'realname',
        valueField: 'id',
        params: { deptId: schema?.deptId },
        immediate: !!schema?.deptId,
      }),
    },
  ],
  labelWidth: 100,
});
</script>
```

## 相关组件

- [[09. BasicForm 表单]] - 表单容器组件
- [[17. JSelectDept 部门选择]] - 部门选择组件
- [[18. JSelectUser 用户选择]] - 用户选择组件
