mapProps
描述
将Field属性与组件属性映射的适配器函数,主要与 connect 函数搭配使用
签名
ts
import { Field, GeneralField } from '@formily/core'
type IStateMapper<Props>
= | {
[key in keyof Field]?: keyof Props | boolean;
}
| ((props: Props, field: GeneralField) => Props)
interface mapProps<T extends Vue.Component> {
(...args: IStateMapper<VueComponentProps<T>>[]): Vue.Component
}- 参数可以传对象(key 是 field 的属性,value 是组件的属性,如果 value 为 true,代表映射的属性名相同)
- 参数可以传函数,函数可以直接对属性做更复杂的映射
用例
<script setup lang="ts">
import type { Field as TypeField } from '@formily/core'
import { createForm, setValidateLanguage } from '@formily/core'
import {
connect,
Field,
FormConsumer,
FormProvider,
mapProps,
} from '@silver-formily/vue'
import { ElButton, ElFormItem, ElInput } from 'element-plus'
setValidateLanguage('en')
const FormItem = connect(
ElFormItem,
mapProps(
{
title: 'label',
description: 'extra',
required: true,
validateStatus: true,
},
(props, field: TypeField) => ({
...props,
help: field.selfErrors?.length ? field.selfErrors : undefined,
}),
),
)
const form = createForm({ validateFirst: true })
function log(...args: unknown[]) {
console.log(...args)
}
function handleSubmit() {
form.submit(log)
}
</script>
<template>
<FormProvider :form="form">
<Form layout="vertical">
<Field
name="name"
title="Name"
required
:decorator="[FormItem]"
:component="[ElInput, { placeholder: 'Please ElInput' }]"
/>
<FormConsumer>
<template #default="{ form: _form }">
<div style="white-space: pre; margin-bottom: 16px">
{{ JSON.stringify(_form.values, null, 2) }}
</div>
<ElButton type="primary" @click="handleSubmit">
Submit
</ElButton>
</template>
</FormConsumer>
</Form>
</FormProvider>
</template><script setup lang="ts">
import type { Field as TypeField } from '@formily/core'
import { createForm, setValidateLanguage } from '@formily/core'
import {
connect,
Field,
FormConsumer,
FormProvider,
mapProps,
} from '@silver-formily/vue'
import { ElButton, ElFormItem, ElInput } from 'element-plus'
setValidateLanguage('en')
const FormItem = connect(
ElFormItem,
mapProps(
{
title: 'label',
description: 'extra',
required: true,
validateStatus: true,
},
(props, field: TypeField) => ({
...props,
help: field.selfErrors?.length ? field.selfErrors : undefined,
}),
),
)
const form = createForm({ validateFirst: true })
function log(...args: unknown[]) {
console.log(...args)
}
function handleSubmit() {
form.submit(log)
}
</script>
<template>
<FormProvider :form="form">
<Form layout="vertical">
<Field
name="name"
title="Name"
required
:decorator="[FormItem]"
:component="[ElInput, { placeholder: 'Please ElInput' }]"
/>
<FormConsumer>
<template #default="{ form: _form }">
<div style="white-space: pre; margin-bottom: 16px">
{{ JSON.stringify(_form.values, null, 2) }}
</div>
<ElButton type="primary" @click="handleSubmit">
Submit
</ElButton>
</template>
</FormConsumer>
</Form>
</FormProvider>
</template>
查看源码