看的是b站视频 Vue实战项目:https://www.bilibili.com/video/BV1E7411c7M8?p=22
下面是看P21-24写的笔记,主要包括axios的用法,我个人对es6和异步函数真的非常不熟悉,所以认真写了很多笔记。
axios
a.引入axios in main.js
import axios from 'axios'
//配置请求根路径
axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1/'
Vue.prototype.$http = axios
b.login异步获取请求的例子
这里的validate是elementui里定义的表单方法
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VmAYsaWh-1645721883680)(C:\Users\11316\AppData\Roaming\Typora\typora-user-images\image-20220224221857626.png)]
this.$refs.loginFormRef.validate( valid =>{})
这里的valid就是boolean,第二个object没有写,然后箭头函数嘛,参数以及=>箭头函数,后面是函数体,慢慢应该就能看习惯了。
this.$http.post(“login”,this.loginForm)
在api接口文档中有写
那么post是请求方法,然后login是请求路径,loginForm在data中定义过,是一个包括username和password的对象,就直接用this.loginForm来作为参数。
const res = this.$http.post(“login”,this.loginForm);
console.log(res)
先打印一下res看会得到什么,发现浏览器会返回一个 Promise结果 。
因为这是一个异步,所以用 async+await 来展现。
await只能用在async修饰的的方法中,所以就应该把valid前面加一个async
this.KaTeX parse error: Expected '}', got 'EOF' at end of input: …=await== this.http.post(“login”,this.loginForm);
console.log(res)
此时打印res之后就会得到具体的axios封装好的响应对象
然后解构一下
const {data:res} = await this.$http.post(“login”,this.loginForm);
console.log(res)
此时打印出来的就是只有data,没有其他我们不需要的数据了
提示弹框登陆成功,登陆失败是怎么做的呢(我这里全局导入了elementui所以其实是可以不用再main.js