最外面包裹的那层“充电费用”是对里面的没有任何影响的,导致我表单验证一直过不去的原因是里面动态表单的name,我写的是name="price",导致表单验证一直无法识别这个name,以为这个动态表单的数据是直接写在addformState下面的。实际上这个数据是在addformState中scBillingInfoDTO数组下面的,所以导致报错。
正确的写法是 :name="['scBillingInfoDTO', index, 'billHour']",这样可以精确查找到每个表单对应的数据
<a-form-item
label="充电费用"
name="scBillingInfoDTO"
:rules="[
{
required: true,
},
]"
>
<div>
<div style="margin-bottom: 10px">
<a-button
shape="circle"
style="border: none; color: #02a7f0"
@click="addSight"
>
<template #icon>
<PlusCircleOutlined />
</template>
添加
</a-button>
</div>
<a-space
v-for="(sight, index) in addformState.scBillingInfoDTO"
:key="sight.id"
style="display: flex; margin-bottom: 8px"
align="baseline"
>
<a-form-item
:name="['scBillingInfoDTO', index, 'billHour']"
label=""
:rules="[
{
required: true,
message: '请输入小时',
},
{
pattern: /^\d+(\.\d{0,2})?$/,
message: '请输入有效的数字,且小数点后最多两位',
},
]"
>
<a-input
v-model:value="sight.billHour"
style="width: 300px"
>
<template #suffix>
<div>小时</div>
</template>
</a-input>
</a-form-item>
<a-form-item
label=""
:name="['scBillingInfoDTO', index, 'price']"
:rules="[
{
required: true,
message: '请填写元',
},
{
pattern: /^\d+(\.\d{0,2})?$/,
message: '请输入有效的数字,且小数点后最多两位',
},
]"
>
<a-input v-model:value="sight.price" style="width: 300px">
<template #suffix>元</template>
</a-input>
</a-form-item>
<a-button
danger
type="primary"
v-if="index > 0"
@click="removeSight(sight)"
>删除</a-button
>
</a-space>
</div>
</a-form-item>
const addformState = reactive({
name: "",
productType: "1",
model: "1",
scBillingInfoDTO: [
{
billHour: "",
price: "",
id: 1,
},
],
});
// 表单新增项
const removeSight = (item) => {
const index = addformState.scBillingInfoDTO.indexOf(item);
if (index !== -1) {
addformState.scBillingInfoDTO.splice(index, 1);
}
};
const addSight = () => {
addformState.scBillingInfoDTO.push({
billHour: "",
price: "",
id: nextId.value++,
});
};