前后端分离,必须知道的axios
1. axios介绍
VUE中结合网络数据进行应用的开发
目前十分流行网络请求库,专门用来发送请求,其内部还是ajax,进行封装之后使用更加方便.
axios作用: 在浏览器中可以帮助我们完成 ajax异步请求的发送.
Vue2.0之后,尤雨溪推荐大家用axios替换JQuery ajax
2. axios入门
使用步骤:
1)导包
<!-- 官网提供的 axios 在线地址 --><script src="https://unpkg.com/axios/dist/axios.min.js"></script>
2)请求方式,以GET和POST举例
GET
axios.get(地址?key=value&key2=value2).then(function(response){},function(error) {});
POST
axios.post(地址,{key:value,key2:value2}).then(function(response) {},function(error){})
3) 根据接口文档, 访问测试接口,进行测试
接口1:随机笑话
请求方法:get
请求参数:num(笑话条数,数字)
响应内容:随机笑话
接口2:用户注册
请求方法:post
请求参数:username(用户名,字符串)
响应内容:注册成功或失败
代码示例
axios接口测试.html
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title><style>/*axios总结1.axios必须要导包2.使用get或者post方式发送请求3.then方法 中的回调函数,会在请求成功或者失败的时候被触发4.通过回调函数的形参,可以获取响应的内容*/</style></head><body><input type="button" value="get请求" id="get" /><input type="button" value="post请求" id="post" /></body><script src="./js/axios.min.js"></script><script>/*随机笑话接口测试请求地址:https://autumnfish.cn/api/joke/list请求方法:get请求参数:num(笑话条数,数字)响应内容:随机笑话*/document.getElementById("get").onclick = function () {axios.get("https://autumnfish.cn/api/joke/list?num=1").then(function (resp) {//调用成功console.log(resp);},function (err) {//调用失败console.log(err);});};/*用户注册请求地址:https://autumnfish.cn/api/user/reg请求方法:post请求参数:username:"用户民"响应内容:注册成功或失败*/document.getElementById("post").onclick = function () {axios.post("https://autumnfish.cn/api/user/reg", { username: "张abc" }).then(function (resp) {console.log(resp);},function (error) {console.log(error);});};</script></html>
3. axios总结
axios 必须导包才能使用
使用get或者post方法,就可以发送请求
then方法中的回调函数,会在请求成功或者请求失败的时候触发
通过回调函数的形参可以获取响应的内容,或者错误信息
4. 获取笑话案例
下面是通过vue+axios 完成一个获取笑话的案例.
1)接口: 随机获取一条笑话
请求方法:get
请求参数:无
响应内容:随机笑话
2)代码示例
笑话案例.HTML
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>vue+axios获取笑话</title><style>/*1.axios回调函数中,this的指向已经改变,无法访问data中的数据2.解决方案: 将this进行保存*/</style></head><body><div id="app"><input type="button" value="点击获取一个笑话" @click="getJoke" /><p>{{joke}}</p></div></body><script src="../js/vue.min.js"></script><script src="../js/axios.min.js"></script><script>/*请求地址:https://autumnfish.cn/api/joke请求方法:get请求参数:无响应内容:随机笑话*/var VM = new Vue({el: "#app",data: {joke: "笑口常开",},methods: {getJoke: function () {//把this进行保存var that = this;//异步访问axios.get("https://autumnfish.cn/api/joke?num=1").then(function (resp) {console.log(resp.data);//在回调函数内部 ,this无法正常使用,需要提前保存起来console.log(that.joke); //undefinedthat.joke = resp.data;},function (error) {});},},});</script></html>
3)运行结果
4)案例总结
axios回调函数中this指向已经改变,无法访问data中的数据
解决方案: 将this进行保存,回调函数中直接使用保存this的变量即可
