使用element-ui框架的积累(一)
自定义表单校验
<template> <div class="login-area container-area"> <h3 class="set-center"> <router-link to="/login">登录</router-link> <el-divider direction="vertical"></el-divider> <router-link to="/register">注册</router-link> </h3> <el-form ref="form" :rules="formRules" :model="form"> <el-form-item prop="username"> <el-input placeholder="用户名" v-model="form.username" clearable prefix-icon="el-icon-user" ></el-input> </el-form-item> <el-form-item prop="password"> <el-input placeholder="密码" v-model="form.password" clearable show-parssword prefix-icon="el-icon-lock" ></el-input> </el-form-item> <el-form-item prop="code"> <el-row> <el-col :span="17"> <el-input placeholder="验证码" v-model="form.code" prefix-icon="el-icon-mobile" ></el-input> </el-col> <el-col :span="7"> <div class="code-area"> <Identity :changeCode.sync="identifyCode"></Identity> </div> </el-col> </el-row> </el-form-item> <el-form-item> <el-button type="primary" @click="onSubmit">登录</el-button> <el-button @click="onReset">重置</el-button> </el-form-item> </el-form> </div> </template> <script> import Identity from "@/components/Identity"; export default { name: "Login", components: { Identity }, data() { const codeValid =(rule, value, callback)=>{ console.log(value) console.log(this.identifyCode) if (value!=this.identifyCode) { callback(new Error("验证码输入错误")); } else { callback(); } }; return { form: { username: "", password: "", code: "" //验证码 }, identifyCode: "", //随机生成的验证码 formRules: { username: [ { required: true, message: "请输入用户名", trigger: "blur" }, { min: 3, max: 10, message: "长度在3-10个字符", trigger: "blur" } ], password: [ { required: true, message: "请输入密码", trigger: "blur" }, { min: 3, max: 10, message: "长度在3-10个字符", trigger: "blur" } ], code: [ { required: true, message: "请输入验证码", trigger: "blur" }, { validator: codeValid, trigger: "blur" } ] } }; }, created() { document.getElementsByTagName("body")[0].style.background = "#f5f5f5"; }, mounted() { console.log(this.identifyCode) }, methods: { // 提交信息 onSubmit() { // console.log(this.$refs["form"]) this.$refs["form"].validate((valid)=>{ if(valid){ alert("submit") }else{ alert("error") } }) }, // 重置信息 onReset() {} } }; </script> <style scoped> .container-area { width: 400px; margin: 0px auto; margin-top: 10%; background-color: #ffff; padding: 20px; } .set-center { text-align: center; font-weight: 500; } .set-center > a { text-decoration: none; color: #409EFF; } .code-area { cursor: pointer; } .router-link-active{ font-weight: bold; } </style>
自定义表单校验的时候
const codeValid =(rule, value, callback)=>{
if (value!=this.identifyCode) {
callback(new Error("验证码输入错误"));
} else {
callback();
}
};
codeValid的结果是一个箭头函数,不然“this.属性名”获取不到data中定义的属性.