目标:Vue 来实现一个简易的登录框,有 用户名(user)和 密码(password),具备简单的校验。
使用的UI框架:ElementUI
vue 登录框的优点:
- 无须操作 dom,只需建立数据模型,自动渲染。
- 双向数据绑定。
登录框的解决点:
- 数据如何绑定
- 登录校验
先上代码:
<template>
<div class="dialog">
<div class="loginPage">
<h1>登录</h1>
<el-form>
<el-form-item label="user">
<el-input type="text" id="user" v-model="formName.user" @blur="inputBlur('user',formName.user)"></el-input>
<p>{{formName.userError}}</p>
</el-form-item>
<el-form-item label="password">
<el-input type="password" id="password" v-model="formName.password" @blur="inputBlur('password',formName.password)"></el-input>
<p>{{formName.passwordError}}</p>
</el-form-item>
<el-button type="primary" @click="submitForm('formName')" v-bind:disabled="formName.beDisabled">提交</el-button>
<el-button @click="resetForm">重置</el-button>
</el-form>
</div>
</div>
</template>
<style scoped>
html,body{
margin: 0;
padding: 0;
position: relative;
}
.dialog{
width: 100%;
height: 100%;
background: rgba(0,0,0,.8);
}
.loginPage{
position: absolute;
top: 50%;
left: 50%;
margin-top: -150px;
margin-left: -175px;
width: 350px;
min-height: 300px;
padding: 30px 20px 20px;
border-radius: 8px;
box-sizing: border-box;
background-color: #fff;
}
.loginPage p{
color: red;
text-align: left;
}
</style>
样式方面在这就不多言了
script部分
<script>
import Axios from 'axios'
export default {
name: '',
data () {
return {
formName: {//表单中的参数
user: '',
userError: '',
password: '',
passwordError: '',
beDisabled: true
},
beShow: false//传值给父组件
}
},
/*props:[
'fromParent'
],*/
methods: {
resetForm:function(){
this.formName.user = '';
this.formName.userError = '';
this.formName.password = '';
this.formName.passwordError = '';
},
submitForm:function(formName){
//与父组件通信传值
//this.$emit('showState', [this.beShow,this.formName.user])
//提交user password
var user = this.formName.user,
password = this.formName.password;
console.log(user,password)
Axios.get('../../src/php/login.php?user='+user+'&password='+password)
.then(function(res){
console.log(res)
})
.catch(function(){
})
},
inputBlur:function(errorItem,inputContent){
if (errorItem === 'user') {
if (inputContent === '') {
this.formName.userError = '用户名不能为空'
}else{
this.formName.userError = '';
}
}else if(errorItem === 'password') {
if (inputContent === '') {
this.formName.passwordError = '密码不能为空'
}else{
this.formName.passwordError = '';
}
}
//对于按钮的状态进行修改
if (this.formName.user != '' && this.formName.password != '') {
this.formName.beDisabled = false;
}else{
this.formName.beDisabled = true;
}
}
}
}
</script>
解释:
1、这边表单中的数据全在 fromName 对象中。
2、对于是 input 框中绑定数据,使用 v-model 双向绑定,效果类似jQuery中的 on(‘input’) 事件。
3、校验判断触发事件: 这边使用的 blur 时触发校验,错误提示绑定 p 元素上。
4、在 blur 事件触发的同时,去判断提交按钮是否可提交,初始换时默认是不可提交 disabled。
5、完成输入和校验成功,点击提交按钮,发起异步请求,这边使用 Axios.get()。
效果:
到此一个简单的登录表单就可以了。
希望对那么可爱,还来看我博客的你 有些许的帮助!