上节课我们用Swagger测试了后端项目的用户登陆Web方法,输入正确的用户名和密码确实能成功登陆系统,并且向前端返回了布尔值和权限列表,本小节我们来实现前端项目的代码。
login.vue页面中包含了两种登陆方式:二维码登陆和帐户登陆。二维码登陆功能已经实现了,这里需要我们实现的是帐户登陆。至于说什么时候显示哪种方式完全是由qrCodeVisible
变量的值来决定的。
<div v-if="!qrCodeVisible"> <!--帐户登陆的内容--> <div class="row"> <el-input v-model="username" placeholder="用户名" prefix-icon="el-icon-user" clearable="clearable" /> </div> <div class="row"> <el-input type="password" v-model="password" placeholder="密码" prefix-icon="el-icon-lock" clearable="clearable" /> </div> <div class="row"> <el-button type="primary" class="btn">登陆系统</el-button> </div> <div class="row"><a class="link" @click="changeMode">二维码登陆</a></div> </div> <div v-if="qrCodeVisible"> <!--二维码登陆的内容--> </div>
代码块预览 复制
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
模型层里面定义了相关的变量,包括文本框输入的内容都会被自动保存在模型层的变量里面。
export default { data: function() { return { username: null, password: null, qrCodeVisible: false, qrCode: '', uuid: null, qrCodeTimer: null, loginTimer: null }; }, …… }
代码块预览 复制
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
1. 引入内容验证库
在src\utils\validate.js
文件中定义了一些验证内容的公共函数,比如验证用户名、密码、邮箱、电话号码。例如下面是我们要调用的验证用户名和密码的函数。
/** * 验证用户名 * @param {Object} s */ export function isUsername(s) { return /^[a-zA-Z0-9]{5,50}$/.test(s) } /** * 验证密码 * @param {Object} s */ export function isPassword(s) { return /^[a-zA-Z0-9]{6,20}$/.test(s) }
代码块预览 复制
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
我们在提交Ajax请求之前,必须先要做前端验证。
<script> import { isUsername, isPassword } from '../utils/validate.js'; …… </script>
代码块预览 复制
- 1
- 2
- 3
- 4
2. 实现登陆功能
我们需要先找到登陆按钮,然后给按钮设置点击事件。
<el-button type="primary" class="btn" @click="login">登陆系统</el-button>
代码块预览 复制
- 1
接下来声明点击事件对应的login()
回调函数。
login: function() { let that = this; if (!isUsername(that.username)) { that.$message({ message: '用户名格式不正确', type: 'error', duration: 1200 }); } else if (!isPassword(that.password)) { that.$message({ message: '密码格式不正确', type: 'error', duration: 1200 }); } else { let data = { username: that.username, password: that.password }; //发送登陆请求 that.$http('user/login', 'POST', data, true, function(resp) { if (resp.result) { //在浏览器的storage中存储用户权限列表,这样其他页面也可使用storage中的数据,实现共享 let permissions = resp.permissions; //取出Token令牌,保存到storage中 let token = resp.token; localStorage.setItem('permissions', permissions); localStorage.setItem('token', token); //让路由跳转页面,这里的Home是home.vue页面的名字 router.push({ name: 'Home' }); } else { that.$message({ message: '登陆失败', type: 'error', duration: 1200 }); } }); } }, ……
代码块预览 复制
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
为了能让Ajax在Header中上传Token令牌,我们找到main.js文件,在里面填上这句话。
3. 执行登陆
访问登陆画面,输入正确的用户名和密码之后,如果浏览器跳转到Home页面,说明咱们的程序没有问题。
如果登陆的时候输入了错误的用户名或者密码,点击登陆按钮,页面依然还是停留在登陆画面。