Vue3+ElementPlus表格table/v-for表单校验
element
A Vue.js 2.0 UI Toolkit for Web
项目地址:https://gitcode.com/gh_mirrors/eleme/element
免费下载资源
·
Element Plus 如果需要对表格/列表数据进行表单校验,首先需要更改 form 绑定的 model 数据
const form = ref({
tableData: [] // 表格数据/需要v-for遍历的数据
})
然后将 el-form-item 的 props 修改为如下(格式:表格数据 + 索引 + 需要校验的值),最后加上 rules。v-for 渲染的表单同此
<el-form-item
:prop="'tableData.' + scope.$index + '.value'"
:rules="formRules.value"
>
<el-input v-model="scope.row.value"></el-input>
</el-form-item>
完整代码
<template>
<div class="p-10">
<div class="mb-4">
<el-button type="primary" @click="handleAdd">Add</el-button>
<el-button @click="handleValidate">Valid</el-button>
</div>
<el-form ref="formRef" :model="form">
<el-table :data="form.tableData" border>
<el-table-column prop="id" label="Id"></el-table-column>
<el-table-column prop="name" label="Name"></el-table-column>
<el-table-column label="Value">
<template #default="scope">
<el-form-item
:prop="'tableData.' + scope.$index + '.value'"
:rules="formRules.value"
>
<el-input v-model="scope.row.value"></el-input>
</el-form-item>
</template>
</el-table-column>
</el-table>
</el-form>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { type FormInstance } from 'element-plus'
const form = ref({
tableData: [
{
id: 1,
name: '1',
value: ''
},
{
id: 2,
name: '2',
value: ''
},
{
id: 3,
name: '3',
value: ''
}
]
})
const formRules = ref({
value: [
{
required: true,
message: 'Please input value',
trigger: 'blur'
}
]
})
const handleAdd = () => {
form.value.tableData.push({
id: form.value.tableData.length + 1,
name: '' + (form.value.tableData.length + 1),
value: ''
})
}
const formRef = ref<FormInstance>()
const handleValidate = () => {
formRef.value.validate((valid) => {
if (valid) {
console.log('success')
} else {
console.log('error')
}
})
}
</script>
示例:
GitHub 加速计划 / eleme / element
54.06 K
14.63 K
下载
A Vue.js 2.0 UI Toolkit for Web
最近提交(Master分支:3 个月前 )
c345bb45
7 个月前
a07f3a59
* Update transition.md
* Update table.md
* Update transition.md
* Update table.md
* Update transition.md
* Update table.md
* Update table.md
* Update transition.md
* Update popover.md 7 个月前
更多推荐
已为社区贡献3条内容
所有评论(0)