本文已参与「新人创作礼」活动,一起开启掘金创作之路
本文主要介绍如何利用element搭建表单结构并进行表单的验证。
1.利用脚手架创建项目,执行vue ui命令,手动安装element组件,按需导入
创建完成后,在src下的plugins目录下有一个element.js文件,在其中按需引入需要的元素。内容如下所示:
import Vue from 'vue'
import {
Button,
Card,
Form,
FormItem,
Input
} from 'element-ui'
Vue.use(Button)
Vue.use(Card)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Input)
2.利用元素搭建表单结构
<template>
<div id="app">
<el-card class="login">
<el-form ref="loginForm" style="margin-top:50px" :model="loginForm" :rules="loginRules">
<el-form-item prop="mobile">
<el-input placeholder="请输入手机号" v-model="loginForm.mobile"></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input placeholder="请输入密码" v-model="loginForm.password"></el-input>
</el-form-item>
<el-button type="primary" style="width:100%" @click="login">登录</el-button>
</el-form>
</el-card>
</div>
</template>
样式如下:
<style scoped>
#app{
width: 100%;
height: 100%;
background-color: skyblue;
display: flex;
justify-content: center;
align-items: center;
}
.login{
width: 440px;
height: 330px;
background-color: white;
}
</style>
3.表单验证功能
(1) el-form中绑定model和rules,model绑定data中的对象,包含的是要检验的几个属性。rules绑定data中的对象,包含要检验的属性对应的具体规则。
(2)el-form-item中prop赋值要检验的属性
(3) el-input中双向绑定要检验的属性
在script中定义手机号和密码的校验规则。
<script>
const checkMobile = function(rule,value,callback){
value.charAt(2)==9?callback():callback(new Error('手机号第三位必须为9'))
}
export default {
name: 'app',
components: {
},
data(){
return{
loginForm:{
mobile:'',
password:''
},
loginRules:{
mobile:[{
required:true,
message:'手机号不可为空',
trigger:'blur'
},{
pattern:/^1[3-9]\d{9}$/,
// 以1开头,第二个数字在3到9之间,之后有9个数字,$结束
message:'手机号格式不正确',
trigger:'blur'
},{
trigger:'blur',
validator:checkMobile
}],
password:[{
required:true,
message:'密码不可为空',
trigger:'blur'
},{
min:6,
max:16,
message:'密码必须在6-16位',
trigger:'blur'
}]
}
}
},
methods:{
login(){
// 1.flag校验
// this.$refs.loginForm.validate(flag=>{
// if(flag){
// console.log('登录成功');
// }else{
// console.log('登录失败');
// }
// })
// 2.promise校验
this.$refs.loginForm.validate().then(()=>{
console.log('登录成功');
}).catch(()=>{
console.log('登录失败');
})
}
}
}
</script>
最后,为登录按钮绑定事件,规定登录成功与否及对应的后续操作。可通过两种方式进行校验。
(1)直接通过validate中的参数进行判断
(2) 通过validate所返回的promise对象进行校验