$inject
本文详解事件回调中 $inject 参数的数据结构及各项属性说明。

数据结构
ts
type Inject = {
api: API, // 表单的 API 实例
rule: Rule[], // 当前表单完整规则数组
self: Rule, // 当前组件的生成规则
option: Object, // 表单全局配置对象
args: any[], // 函数的原始参数数组
}重要说明
$inject 是 FormCreate 设计器在事件回调中自动注入的参数对象,它提供了访问表单 API、规则、配置等核心功能的能力。正确使用 $inject 可以大大增强组件的交互性和数据处理能力。
示例 1: 调用 API 方法
js
const api = $inject.api;
const formData = api.formData();常用 API 方法
js
// 获取表单数据
const formData = $inject.api.formData();
// 设置表单数据
$inject.api.setValue({ field: 'value' });
// 获取指定字段的值
const fieldValue = $inject.api.getValue('fieldName');
// 设置指定字段的值
$inject.api.setValue('fieldName', 'newValue');
// 验证表单(返回 Promise)
$inject.api.validate().then(isValid => {
console.log('验证结果:', isValid);
}).catch(error => {
console.error('验证失败:', error);
});
// 重置表单
$inject.api.resetFields();示例 2: 获取事件的原始参数
例如组件触发 change 事件时,会传递出当前的 value 值。
js
emit('change', value);
//or
//props.change(value);获取 value 值
js
const value = $inject.args[0];如果事件存在多个参数时
js
emit('beforeUpload', file, fileList);
//or
//props.beforeUpload(file, fileList);获取参数
js
const file = $inject.args[0];
const fileList = $inject.args[1];示例3: 修改当前组件规则
例如当 value 修改后通过接口修改组件状态
js
const api = $inject.api;
const value = $inject.args[0];
api.fetch({
action: '/api/getdata',
query:{
value
}
}).then(res=>{
//修改自己
$inject.self.options = res.data;
//修改其他组件
$inject.api.getRule('name').value = res.name;
})

