动态计算
动态计算主要用于解决配置需要动态变化的问题是fs-crud
最重要的特性之一
配置动态变化可以有如下4种方式实现:
- 直接修改
crudBinding
对应的属性值。比如crudBinding.value.search.show=false
即可隐藏查询框。 - 给属性配置
ref、computed
类型的值,通过修改ref.value
,就能够动态变化。 compute
同步计算,类似computed
,不同的是它可以根据上下文进行动态计算。asyncCompute
异步计算,基于watch 和 computed
实现,与compute
相比,它支持异步计算。
compute
同步计算常见的需求:
一个用户表,有个用户类型字段userType
,可能的值为:公司
或个人
。 我们要实现,当选择公司
时,需要额外上传营业执照
、填写信用代码
的功能。 就需要在userType
字段选中公司
的时候,将上传营业执照
和信用代码
的输入框显示出来。选择个人
时则不显示。
js
import {useCompute} from '@fast-crud/fast-crud'
const {compute} = useCompute()
const crudOptions = {
columns:{
userType:{
title: '用户类型',
type: 'dict-select',
dict: dict({data:[
{value:1,label:'个人'},
{value:2,label:'公司'}
]})
},
businessLicenceImg :{
title: '营业执照上传',
type: 'avatar-uploader',
form:{
show:compute((context)=>{
// 通过动态计算show属性的值,当前表单内的userType值为公司,才显示此字段
return context.form.userType ===2
})
}
},
businessLicenceCode :{
title: '营业执照号码',
type: 'text',
form:{
show:compute((context)=>{
// 通过动态计算show属性的值,当前表单内的userType值为公司,才显示此字段
return context.form.userType ===2
})
}
}
}
}
用户类型(userType
)是一个下拉选择框,当用户选择不同的值时会改变form.userType
的值,同时会触发businessLicenceImg
和businessLicenceCode
这两个字段中form.show
的重新计算。 从而让营业执照上传和营业执照号码根据userType
的值不同而显隐。
asyncCompute
异步计算:
当我们要计算的值需要从网络请求或者从其他地方异步获取时可以使用此方法配置
- 方法:
asyncCompute({watch?,asyncFn})
- 参数
watch
:Function(context)
,可为空,监听一个值,当这个返回值有变化时,触发asyncFn
。不传则asyncFn
只会触发一次 - 参数
asyncFn
:asyncFn:Function(watchValue, context)
,异步获取值
js
import {compute} from '@fast-crud/fast-crud'
const crudOptions = {
columns:{
grade:{
title: '年级',
type: 'text',
form: {
component:{
name:'a-select',
// 配置异步获取选择框的options
options: asyncCompute({
// 没有配置watch,只会触发一次
asyncFn: async ()=>{
// 异步获取年级列表,这里返回的值将会赋给a-select的options
return request({url:"/getGradeList"})
}
})
}
}
},
class :{
title: '班级',
type: 'avatar-uploader',
form:{
component:{
name:'a-select',
// 配置异步获取选择框的options
options: asyncCompute({
// 监听form.grade的值
watch((context)=>{
return context.form.grade
}),
// 当watch的值有变化时,触发asyncFn,获取班级列表
asyncFn: async (watchValue,context)=>{
// 这里返回的值 将会赋值给a-select的options
return request({"/getClassList?grade=" + watchValue})
}
})
}
}
},
}
}
只有在需要用到行数据(row
)、表单数据(form
)参与动态计算的地方,才使用compute
和asyncCompute
,其他时候使用ref
或computed