环境配置
- 终端中输入
npm i element-ui -S - 在main.js中全局引入
【html写法】
<el-form
:model="ruleForm"
status-icon
:rules="rules"
ref="ruleForm"
label-width="100px"
class="demo-ruleForm"
>
<el-input v-model="ruleForm.email"
autocomplete="off">
<el-input
type="password"
v-model="ruleForm.password"
autocomplete="off">
<el-input
type="password"
v-model="ruleForm.checkpass"
autocomplete="off">
<el-button type="primary" @click="submitForm('ruleForm')"
>提交</el-button
>
<el-button @click="resetForm('ruleForm')">重置
【script写法】
export default {
name: "App",
data() {
var checkAge = (rule, value, callback) => {
if (!value) {
return callback(new Error("用户名不能为空"));
} else {
callback();
}
};
var checkEmail = (rule, value, callback) =>{
if(value ===''){
return callback(new Error('邮箱不能为空'))
}else if ( !/^\w*@[a-z0-9A-Z]*.com$/.test(value)){
return callback(new Error('邮箱必须包含"@"和"."'))
}else{
callback();
}
};
var validatePass = (rule, value, callback) => {
if (value === "") {
callback(new Error("密码不能为空"));
} else {
callback();
}
};
var validatePass2 = (rule, value, callback) => {
if (value === "") {
callback(new Error("密码不能为空"));
} else if (value !== this.ruleForm.password) {
callback(new Error("两次输入密码不一致!"));
} else {
callback();
}
};
return {
ruleForm: {
username: "",
email: "",
password: "",
checkpass: "",
},
rules: {
username: [{ validator: checkAge, trigger: "blur" }],
email: [{ validator: checkEmail, trigger: "blur" }],
password: [{ validator: validatePass, trigger: "blur" }],
checkpass: [{ validator: validatePass2, trigger: "blur" }],
},
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert("submit!");
} else {
console.log("error submit!!");
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
},
},
};
【css写法】
.demo-ruleForm {
width: 600px;
margin: 50px auto;
}