文章目录
vue:3.x
element-plus:2.7.3
重点:
1) tableData放到form对象里
2) form-item的prop要写成tableData.序号.属性
<!--table-表单校验-->
<template><el-form ref="forms" :model="form"><el-table :data="form.tableData" style="width: 100vw"><el-table-column :label="col.label" v-for="col in cols"><template #default="scope"><div v-if="scope.row.isEdit"><el-form-item :prop="`tableData.${scope.$index}.${col.field}`" :rules="rules[col.field]"><el-input v-model="scope.row[col.field]" :placeholder="`请输入${col.label}`" /></el-form-item></div><div v-else>{{ scope.row[col.field] }}</div></template></el-table-column><el-table-column fixed="right" label="Operations"><template #default="scope"><el-button link type="primary" size="small" @click="edit(scope)">Edit</el-button><el-button link type="primary" size="small" @click="save(scope)">Save</el-button></template></el-table-column></el-table><el-form-item><el-button type="primary" @click="submitForm(forms)">Submit</el-button><el-button @click="resetForm(forms)">Reset</el-button></el-form-item></el-form>
</template><script lang="ts" setup>
import { FormInstance, FormRules } from 'element-plus';
import { onMounted, reactive } from 'vue';import { ref } from 'vue'const forms = ref < FormInstance > ()
const form = ref({ tableData: [] })
const rules = reactive < FormRules > ({name: [{ required: true, message: "请输入姓名", trigger: "blur" },],cardId: [{ required: true, message: "请输入身份证", trigger: "blur" },{ pattern: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur' }],
})const cols = [{ field: 'name', label: '姓名' },{ field: 'city', label: '城市' },{ field: 'cardId', label: '身份证' },
]onMounted(() => {form.value.tableData = [{name: 'Tom',city: 'Los Angeles',cardId: 331022100040284032,isEdit: false},{name: 'Tom',city: 'Los Angeles',cardId: 331022100040284032,isEdit: false},]
})const edit = (scope) => {console.log(scope, 'scope')scope.row.isEdit = true
}const save = async (scope) => {console.log(scope, 'scope')// scope.row.isEdit = falseif (!forms) returnconsole.log(form.value, forms, 'form')await forms.value.validate(async valid => {console.log(valid, 'valid')})
}const submitForm = (formEl: FormInstance | undefined) => {if (!formEl) returnformEl.validate((valid) => {if (valid) {console.log('submit!',form.value)} else {console.log('error submit!',form.value,formEl)}})
}const resetForm = (formEl: FormInstance | undefined) => {if (!formEl) returnformEl.resetFields()
}
</script><style scoped lang="less"></style>