使用 slot 自定义控件
NForm
对于每个表单项都提供了三个 slot, 分别是: ${name}Label
, ${name}Control
, ${name}
, 分别对应表单项的 label, control, 整个表单项.
TIP
自定义的控件请使用 slot 提供的 formData
绑定数据.
formData
是内部表单数据的代理对象, 对 formData
的赋值操作会被监听并触发表单更新.
自定义整个表单项
vue
<script>
import { ref, watch } from "vue";
import { FormItemControlType } from "@nbicc/common-components";
const data = ref({});
watch(data, () => console.log(data.value), { deep: true });
const fields = ref([
{ name: "input", label: "输入框", type: FormItemControlType.INPUT },
{ name: "input-number", label: "数字输入框", type: FormItemControlType.INPUT_NUMBER }
]);
</script>
<template>
<NForm v-model:data="data" :fields="fields">
<template #input="{ field, formData }">
// 自定义 name 为 "input" 的表单项
<a-form-item :label="field.options.label">
<a-input v-model:value="formData.input" placeholder="自定义的 placeholder" />
</a-form-item>
</template>
</NForm>
</template>
分开自定义表单项的 label 和 control
vue
<script>
import { ref, watch } from "vue";
import { FormItemControlType } from "@nbicc/common-components";
const data = ref({});
watch(data, () => console.log(data.value), { deep: true });
const fields = ref([
{ name: "input", label: "输入框", type: FormItemControlType.INPUT },
{ name: "input-number", label: "数字输入框", type: FormItemControlType.INPUT_NUMBER }
]);
</script>
<template>
<NForm v-model:data="data" :fields="fields">
<!-- 自定义 label -->
<template #inputLabel="{ field }">自定义的 label</template>
<!-- 自定义 control -->
<template #inputControl="{ field, formData }">
<a-input v-model:value="formData.input" placeholder="自定义的 placeholder" />
</template>
</NForm>
</template>