具体需求:实现可添加行数据的表单,并且能够单独校验一行的数据,废话不多说,直接上代码
<template>
<el-form
ref="busiKeyFormRef"
:model="busiKeyTableForm"
>
<el-table
class="myTable"
border
:data="busiKeyTableForm.tableData"
v-loading="busiKeyLoading"
:header-cell-style="{ height: '48px' }"
row-class-name="rowClass"
>
<el-table-column v-for="(item, index) in busiKeyCol" :key="index" v-bind="item">
<template #default="{row, $index}">
<template v-if="row.isEdit">
<el-form-item
:prop="'tableData.'+ $index + '.' + item.prop"
:rules="busiKeyRules[item.prop]"
>
<el-input
v-if="item.formType === 'input'"
v-model="row[item.prop]"
clearable
:placeholder="`请输入${item.label}`"
></el-input>
<el-select
class="w100precent"
v-else-if="item.formType === 'select'"
v-model="row[item.prop]"
clearable
:placeholder="`请选择${item.label}`"
>
<el-option v-for="o in item.selectOption" :key="o.key" :value="o.key" :label="o.name" />
</el-select>
</el-form-item>
</template>
<template v-else>
{{ row[item.prop] }}
</template>
</template>
<template #default="{row, $index}" v-if="item.prop === 'action'">
<el-link type="primary" @click="rowSaveMethod(row, $index)">保存</el-link>
<el-link>取消</el-link>
</template>
</el-table-column>
</el-table>
</el-form>
</template>
这里用的vue3选项式用法,小伙伴们可自行替换成setup语法糖使用
export default {
data() {
return {
busiKeyCol: [{
prop: "THR_KEY",
label: "数据1",
formType: "input",
"min-width": 200,
}, {
prop: "ITE_KEY",
label: "数据2",
formType: "input",
"min-width": 200,
}, {
prop: "WJ_KEY",
label: "数据3",
formType: "input",
"min-width": 200,
}, {
prop: "KEY_TYPE",
label: "数据4",
formType: "select",
selectOption: [{
key: "string",
name: "字符串"
}, {
key: "number",
name: "数字"
}],
"min-width": 200,
}, {
prop: "INDEX",
label: "数据5",
formType: "input",
"min-width": 100,
}, {
prop: "action",
label: "操作",
fixed: "right",
}],
busiKeyRules: {
THR_KEY: [{ required: true, message: "请输入", trigger: "blur" }],
ITE_KEY: [{ required: true, message: "请输入", trigger: "blur" }],
WJ_KEY: [{ required: true, message: "请输入", trigger: "blur" }],
KEY_TYPE: [{ required: true, message: "请选择", trigger: "change" }],
INDEX: [{ required: true, message: "请输入", trigger: "blur" }],
},
busiKeyTableForm: {
tableData: [],
},
};
},
methods: {
async rowSaveMethod(row, index) {
const { isEdit, ...partial } = row;
const props = Object.keys(partial).map(item => `tableData.${index}.${item}`);
const valid = await this.$refs.busiKeyFormRef.validateField(props, async(valid) => await valid);
console.log("valid", valid); // 校验结果
},
},
}
最后效果