前言
本节笔记记录了如何更加完善这个管理系统的登录页面。
主要实现登录前的预校验,以及发起网络请求并返回结果。
一、认识登录前的预校验语法
this.$refs.LoginFormRef.vaildate((vaild)=>{
console.log(vaild)
}
这是一个回调函数:
它对整个表单进行校验的方法,参数为一个回调函数。该回调函数会在校验结束后被调用,并传入两个参数:是否校验成功和未通过校验的字段。若不传入回调函数,则会返回一个 promise
Function(callback: Function(boolean, object))
其中使用了箭头函数进行简化
二、实际开发中使用
1.发送网络请求的配置
- 首先需要引入axios,需要在main.js中引入并挂载到Vue的原型对象上
import axios from 'axios' Vue.prototype.$http = axios
- 设置请求的根目录
axios.defaults.baseURL = "后端的API接口地址"
2.完善登录方法
- 在methods中添加方法login(),严格按照登录前的预校验语法格式进行编写
login(){ this.$refs.LoginFormRef.vaildate((vaild)=>{ console.log(vaild) }
- 发送网络请求
this.$refs.LoginFormRef.vaildate((vaild)=>{ if(!vaild) return; const result = this.$http.post('login',this.form) console.log(result) }
这样写完后返回的是一个promise对象我们可以使用async和await进行简化
- 简化函数
this.$refs.LoginFormRef.vaildate( async (vaild)=>{ if(!vaild) return; const result = await this.$http.post('login',this.form) console.log(result) }
使用async异步后,返回的就是一个具体的响应对象了,我们需要的只有data属性,接下来进一步进行简化——解构赋值。
4.解构赋值
this.$refs.LoginFormRef.vaildate( async (vaild)=>{
if(!vaild) return;
const {data:res} = await this.$http.post('login',this.form)
console.log(res)
}
3.美化输出结果
- 在element.js中全局引入message控件
import {Message} from 'element-ui' Vue.prototype.$message = Message
- 通过postman对后端输出的结果进行分析,可以得到res中的meta中的status值表示着是否登录成功,我们可以使用这个值进行可视化的显示。(因后端而异)
this.$refs.LoginFormRef.vaildate( async (vaild)=>{ if(!vaild) return; const {data:res} = await this.$http.post('login',this.form) if(res.meta.status!==200) return this.$message.error(res.meta.msg) this.$message.success(res.meta.msg) }