Skip to content

自定义适配器

自定义数据源转换为字典格式。

字典适配器模式

typescript
import type { DictAdapterConfig } from "vue-admin-kit";

const customAdapters: Record<string, DictAdapterConfig> = {
  user_list: {
    api: () => getUserList(),
    params: () => ({ status: "1" }),
    transform: (res) =>
      res.data.map((item) => ({
        label: item.name,
        value: String(item.id),
      })),
  },
};

注册适配器

typescript
setupPageTemplate({
  dependencies: {
    customAdapters: {
      // 自定义适配器:保险专员
      insurance_commissioner: {
        api: () => getCommissionerList(),
        params: () => ({ roleCode: "commissioner" }),
        transform: (response) => {
          const data = response?.data || response;
          return data.map((item: any) => ({
            label: item.name,
            value: String(item.id),
          }));
        },
      },
      // 自定义适配器:产品列表
      product_list: {
        api: () => getProductList(),
        transform: (response) => {
          return response.data.map((item: any) => ({
            label: item.productName,
            value: String(item.productId),
            raw: item, // 保留原始数据
          }));
        },
      },
    },
  },
});

使用自定义适配器

在配置中使用 dictType 指定适配器名称:

typescript
const searchConfig = defineSearchConfig([
  {
    type: "select",
    prop: "commissionerId",
    label: "保险专员",
    dictType: "insurance_commissioner",
    filterable: true,
  },
]);

const formConfig = defineFormConfig([
  {
    type: "select",
    prop: "productId",
    label: "产品",
    dictType: "product_list",
    filterable: true,
  },
]);

适配器配置项

typescript
interface DictAdapterConfig {
  // API 调用函数
  api: () => Promise<any>;

  // 可选:API 参数
  params?: () => Record<string, any>;

  // 数据转换函数
  transform: (response: any) => DictDataOption[];
}

interface DictDataOption {
  label: string;
  value: string;
  elTagType?: "success" | "warning" | "danger" | "info" | "";
  raw?: any; // 原始数据
}

Released under the MIT License.