# 计算字段

当一个字段的值是通过其它多个字段计算获得时,开发者可以使用计算字段属性 computeFrom 进行实现。

# 属性说明

属性名 属性值说明 默认值
fields [Array] 绑定计算字段
trigger [String] 指定计算函数执行的时机
可选值:input change blur
change
computer [Function|String|Array] 计算函数
计算函数携带与绑定的计算字段相关的多个参数。每个参数为一个对象,包含 valueoption 属性。
- value: 绑定字段的当前值
- option: 绑定字段当前选中的选项对象,字段类型为 select/checkbox/radio 时有效
计算函数应当始终返回一个该字段可接受的值。

计算函数的配置方式

通常情况下可将计算函数直接配置为一个函数。在某些情况下,比如表单的配置项通过接口返回,由于接口不支持直接传递函数,因此还可以配置为数组或数组字符串:

{
  fields: ['custType', 'custType2'],
  // 配置为数组,尾元素为函数体,其他元素为参数,主要用在需要接口返回表单配置项的情况
  computer: [
    "custType",
    "custType2",
    "if (!custType.option || !custType2.option) return '';return `客户类型:${custType.option.label}/${custType2.option.label}`"
  ]
}
1
2
3
4
5
6
7
8
9

或者:

{
  fields: ['custType', 'custType2'],
  // 配置为数组字符串,尾元素为函数体,其他元素为参数,主要用在需要接口返回表单配置项的情况
  computer: '["custType","custType2","if (!custType.option || !custType2.option) return \'\';return `客户类型:${custType.option.label}/${custType2.option.label}`"]'
}
1
2
3
4
5

计算函数的参数

计算函数的参数与绑定的字段列表有关,参数的顺序与绑定的字段顺序一致。

# 示例

const formFields = [
  {
    label: '客户大类',
    field: 'custType',
    type: 'select',
    value: '',
    options: []
  }, {
    label: '客户细类',
    field: 'custType2',
    type: 'select',
    value: '',
    options: []
  }, {
    label: '备注',
    field: 'remark',
    value: '',
    innerType: 'textarea',
    computeFrom: {
      // 绑定客户大类、客户细类连个字段进行计算
      fields: ['custType', 'custType2'],
      // 当上述两个字段抛出 change 事件时执行下面定义的计算函数
      trigger: 'change',
      // 计算函数
      computer: (custType, custType2) => {
        // 如果有字段为选中,则返回空字符串
        if (!custType.option || !custType2.option) return ''
        // 反之则返回使用客户类型描述拼接的字符串
        return `客户类型:${custType.option.label}/${custType2.option.label}`
      }
    }
  }
]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
最后更新: 11/18/2021, 11:31:19 AM