具体代码如下:
( 主要是name的取值问题,要严格按照['数据源',index,'校验的字段']来)
<a-form ref="formPackage" :model="formData" :rules="rules">
<a-table :pagination="false" bordered :data-source="formData.dataSource" :columns="columns">
<template #bodyCell="{ column, text, index, record }">
<template v-if="column.dataIndex === 'quantity'">
<div class="editable-cell">
<div class="editable-cell-input-wrapper">
<a-form-item :name="['dataSource', index, 'quantity']" :rules="rules.quantity">
<a-input v-model:value="record.quantity" />
</a-form-item>
</div>
</div>
</template>
<template v-if="column.dataIndex === 'meter'">
<div class="editable-cell">
<div class="editable-cell-input-wrapper">
<a-form-item :name="['dataSource', index, 'meter']" :rules="rules.meter">
<a-input v-model:value="record.meter" />
</a-form-item>
</div>
</div>
</template>
<template v-if="column.dataIndex === 'type'">
<div class="editable-cell">
<div class="editable-cell-input-wrapper">
<a-form-item :name="['dataSource', index, 'type']" :rules="rules.type">
<a-select ref="select" v-model:value="record.type" style="width: 120px">
<a-select-option v-for="(item, index1) in typeData" :value="item.value" :key="index1">{{
item.label
}}</a-select-option>
</a-select>
</a-form-item>
</div>
</div>
</template>
<template v-if="column.dataIndex === 'remark'">
<div class="editable-cell">
<div class="editable-cell-input-wrapper">
<a-form-item>
<a-input v-model:value="record.remark" />
</a-form-item>
</div>
</div>
</template>
<template v-else-if="column.dataIndex === 'operation'">
<a-popconfirm title="确定删除吗?" @confirm="onDelete(index)">
<a-form-item>
<a style="color: red">删除</a>
</a-form-item>
</a-popconfirm>
</template>
</template>
</a-table>
</a-form>
const formPackage = ref()
const formData = ref({
dataSource: []
})
const rules = ref({
quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
meter: [{ required: true, message: '请输入米数', trigger: 'blur' }],
type: [{ required: true, message: '请选择方式', trigger: 'blur' }]
})
const columns = [
{
title: '数量',
dataIndex: 'quantity',
resizable: true
},
{
title: '米数',
dataIndex: 'meter',
resizable: true
},
{
title: '方式',
dataIndex: 'type',
resizable: true
},
{
title: '备注',
dataIndex: 'remark',
resizable: true
},
{
title: '操作',
dataIndex: 'operation',
resizable: true,
width: 80
}
]
const onDelete = (key: string) => {
console.log(key)
if (formData.value.dataSource.length == 1) {
formData.value.dataSource = []
} else {
formData.value.dataSource.splice(key, 1)
}
}
const handleAdd = () => {
const newData = {
quantity: null,
meter: null,
type: '',
remark: ''
}
formData.value.dataSource.push(newData)
}
function handleSubmit() {
let checkRules = await formPackage.value.validate()
}