Web前端-vue+element表单rules验证(多重object)
Posted MinggeQingchun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Web前端-vue+element表单rules验证(多重object)相关的知识,希望对你有一定的参考价值。
element的表单验证用的是async-validator, 官方说明文档地址:GitHub - yiminghe/async-validator: validate form asynchronous
1、data中数据
data()
return
ruleForm:
account:null,
dept:
deptName:null,
deptCode:null,
,
,
rules:
//type默认是string
account: required: true, message: '账户不能为空', trigger: 'blur' ,
//有多条校验条件的时候可以放个object数组
'dept.deptName':[type: "string", required: true, message: '部门名称不能为空', trigger: 'blur'],
'dept.deptCode': type: "string",required: true, message: '部门编码不能为空', trigger: 'blur',
,
2、 template中代码
注:prop中, dept下的属性, 要加上前缀 "dept." , account直接写account,数据是从rulesForm下开始算起
<!-- 添加 账户 对话框 -->
<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
<el-form ref="ruleForm"
:model="ruleForm"
:rules="rules"
label-width="80px">
<el-form-item label="部门编码" prop="dept.deptCode">
<el-input v-model="ruleForm.dept.deptCode" placeholder="请输入部门编码" @click.native="handlerProductList" :disabled="!allowEditProduct" />
</el-form-item>
<el-form-item label="部门名称" prop="dept.deptName">
<el-input v-model="ruleForm.dept.deptName" placeholder="请输入部门名称" @click.native="handlerProductList" :disabled="!allowEditProduct" />
</el-form-item>
<el-form-item label="账户" prop="account">
<el-input v-model="ruleForm.account" placeholder="请输入账户" />
</el-form-item>
<el-form-item label="备注" prop="remark">
<el-input v-model="ruleForm.remark" placeholder="请输入备注" />
</el-form-item>
</el-form>
</el-dialog>
3、methods方法提交
注:
(1)在表单重置 reset() 方法中,需要将数据data() 方法中也需要写入dept对象,this.ruleForm表单清空,不然会报错:
deptName:null,
deptCode:null,
,
[Vue warn]:Error in render: "TypeError: Cannot read property 'XX' of undefined"
(2)rules只是规则,要实现,必须使用validate函数执行规则
methods:
// 取消按钮
cancel()
this.open = false;
this.reset();
,
// 表单重置
reset()
this.ruleForm:
account:null,
dept:
deptName:null,
deptCode:null,
,
;
this.resetForm("form");
,
/** 新增按钮操作 */
handleAdd()
this.reset();
this.open = true;
this.title = "添加账户";
,
/** 提交按钮 */
submitForm()
this.$refs["ruleForm"].validate(valid =>
if (valid)
if (this.ruleForm.userId != null)
updateUser(this.ruleForm).then(response =>
this.msgSuccess("修改成功");
this.open = false;
this.getList();
);
else
addUser(this.ruleForm).then(response =>
this.msgSuccess("新增成功");
this.open = false;
this.getList();
);
);
,
可参考
以上是关于Web前端-vue+element表单rules验证(多重object)的主要内容,如果未能解决你的问题,请参考以下文章