Skip to content

组件加载远程数据

FormCreate 中,fetch 属性提供了强大的功能,允许从远程 API 加载数据并将其应用到表单组件中。通过灵活的配置,fetch 可以在多种场景下发挥作用,从简单的选项加载到复杂的动态数据处理。

此功能内部是通过自定义属性方式实现。

数据类型

以下是 fetch 属性的详细类型定义:

ts
type Fetch = {
  //接口地址
  action: String;
  //数据插入的位置,例如 'options' 或 'props.options'
  to?: String;
  //请求发送前的回调, 返回 false 可以中断请求
  beforeFetch?: ( config: Object, rule:Rule, api:Api) => void|boolean|Promise;
  //解析接口返回的数据,返回最终需要的结果,默认取 `res.data`
  parse?: String | ((body: any, rule:Rule, api:Api) => any);
  //请求方式,默认值为 'GET'
  method?: String;
  //请求时的GET参数
  query?: Object;
  //请求时附带的数据
  data?: Object;
  //调用接口附带数据的提交方式,默认为 `formData`
  dataType?: 'json' | 'formData';
  //自定义请求头信息
  headers?: Object;
  //请求失败时的回调函数
  onError?: (e: Error | ProgressEvent) => void;
 }

注意

如需将请求 body 设置为 JSON 格式,需定义 dataType 为 'json' 参数。

重写内置的请求方法

在一些高级场景中,您可能需要自定义请求方式。通过在 main.js 文件中重写 formCreate.fetch 方法,您可以自由定义请求的逻辑。

js
const globalFetch = formCreate.fetch;
formCreate.fetch = (config) => {
    config.headers.token = getCookie('user-token');
    return globalFetch(config);
}

注意

文件上传操作同样会调用 fetch 方法,需注意其特殊适配要求,具体实现可参考内置请求模块

示例

通过接口加载数据

通过自定义方法加载数据

发送 POST 请求

js
const rules = [
    {
        type: 'select',
        field: 'product',
        title: '选择产品',
        fetch: {
            action: '/api/products',
            to: 'options',
            type: 'POST',
            dataType: 'json',
            data: {
                Authorization: 'Bearer your-auth-token'
            },
            parse: (res) => res.data.map(product => ({ label: product.name, value: product.id })),
            onError: (error) => console.error('加载产品数据失败:', error)
        }
    }
]

自定义请求头信息

js
const rules = [
    {
        type: 'select',
        field: 'product',
        title: '选择产品',
        fetch: {
            action: '/api/products',
            to: 'options',
            headers: {
                Authorization: 'Bearer your-auth-token'
            },
            parse: (res) => res.data.map(product => ({ label: product.name, value: product.id })),
            onError: (error) => console.error('加载产品数据失败:', error)
        }
    }
]

在请求前设置 Token

在发送 API 请求之前,动态添加 Authorization token 到请求头中。

js
// 配置表单创建的全局选项
const formOptions = {
    // 在请求发送前的钩子
    beforeFetch: (options) => {
        // 动态设置请求头中的 Authorization token
        const token = 'your-auth-token'; // 这里的 token 可以从任何存储中获取
        options.headers = {
            Authorization: `Bearer ${token}`
        };
    }
};
// 创建表单
const rules = [
    {
        type: 'select',
        field: 'product',
        title: '选择产品',
        fetch: {
            action: '/api/products',
            to: 'options',
            parse: (res) => res.data.map(product => ({ label: product.name, value: product.id })),
            onError: (error) => console.error('加载产品数据失败:', error)
        }
    }
];

详细步骤

  1. 设置全局 formOptions: 通过设置全局的 beforeFetch 方法,可以确保在所有带有 fetch 的组件中,都会执行这个钩子。

  2. 动态获取 token: 在 beforeFetch 中,我们可以从存储、Vuex 或其他来源动态获取 token,然后将其添加到请求头中。

  3. 创建表单并使用 fetch: 表单组件中的 fetch 会自动触发 beforeFetch 方法,附加上设置的 Authorization token。

重写内置请求方法并设置 Token

在表单的所有 API 请求中,自动附加 Authorization token 到请求头中,以确保所有请求都携带有效的身份验证信息。

main.js 文件

js
import formCreate from '@form-create/element-ui'; // 假设使用 Element UI


const globalFetch = formCreate.fetch;
// 重写 formCreate 的内置 fetch 方法
formCreate.fetch = (config) => {
    // 获取或生成 Token
    const token = 'your-auth-token'; // 这里的 token 可以从 Vuex、localStorage 或其他地方获取
    // 设置请求头,附加 Authorization token
    config.headers.Authorization = `Bearer ${token}`;
    const headers = {
        ...config.headers,
        Authorization: `Bearer ${token}`,
    };
    return globalFetch(config);
};


// 创建表单
const api = formCreate.create([
    {
        type: 'select',
        field: 'product',
        title: '选择产品',
        fetch: {
            action: '/api/products',
            to: 'options',
            parse: (res) => res.data.map(product => ({ label: product.name, value: product.id })),
            onError: (error) => console.error('加载产品数据失败:', error),
        },
    },
], {
    // 其他表单配置
});

详细步骤

  1. 重写 fetch 方法: 在初始化时,重写 formCreate.fetch 方法,确保所有请求都使用这个自定义的方法。

  2. 设置 Authorization token: 在每次请求中,从存储中获取或生成 token,并将其附加到 headers 中。

  3. 发起请求并处理响应: 根据 options 中的 method、action、data 等参数,发起请求并处理响应数据。

FormCreate 是一个开源项目,基于 MIT 许可证发布,欢迎个人和企业用户免费使用