form表单校验
表单中设置必选项,当必选项未填信息时弹出指定的错误信息,阻止用户提交请求。
1.在html种写弹框
:ref 绑定控件,$refs
获取控件 (*该例中不带冒号绑定选择直接传参)
:model=“绑定数据”
:rules=“验证规则”
<el-dialog title="添加申请" :visible.sync="dialogVisible" width="40%" :close-on-click-modal="false" :before-close="handleClose">
<el-form ref="submitForm" :model="submitForm" :rules="ruless" label-width="30%" label-position="left" class="form-div" size="small">
<el-form-item label="name" prop="name">
<el-input v-model="submitForm.name" prop="name" size="small" placeholder="请输入name"></el-input>
</el-form-item>
<el-form-item label="password" prop="password">
<el-input v-model="submitForm.password" size="small" placeholder="请输入password" ></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="remove()">取 消</el-button>
<el-button @click="reset('submitForm')">重置</el-button>
<el-button type="primary" @click="sure('submitForm')">确 定</el-button>
</span>
</el-dialog>
2.在data种定义绑定的对象,声明规则
ruless:每一条对象对应一个必选项,required为true时显示星号(*),message:弹出的错误信息。
data() {
return {
submitForm:{
name:'',
password:'',
},
ruless: {
name: [{ required: true, message: '请输入name', trigger: 'blur' }],
password: [{ required: true, message: '请输入password', trigger: 'blur' }],
},
dialogVisible:false,
}
3.method方法中写函数
methods: {
//button按钮点击弹出弹框
test(){
this.dialogVisible = true
},
//确认添加
sure(submitForm){
this.$refs[submitForm].validate((valid) => {
console.log(valid)
if (valid) {
alert('验证通过!');
//可写执行添加的方法
} else {
console.log('验证失败!');
return false;
}
});
},
//重置表单
reset(submitForm) {
this.$refs[submitForm].resetFields();
},
//取消表单
remove() {
this.$refs.form.resetFields()//表单验证在关闭时恢复初始值
this.dialogVisible = false;
submitForm={
name:'',
password:'',
},
this.editFlag = false;
},
}
完结。。。