4.2 axios模块
vue使用axios发送http请求,如下所示:
let url="https://www.codessp.cn/api/queryStudentsStatistic?chapterId=766&classId=68&courseId=31";axios({ headers:{ "Content-Type":"application/x-www-form-urlencoded", }, method:"get", url:url, params:{ 参数1:参数值, 参数2:参数值, 参数3:参数值 }}).then((response)=>{ //打印从http获取的数据 conosle.log(response.data); let data=response.data.data; this.chapterStudies=data.chapterStudies;});
如果以post方式发送,只需要把method参数改成post就可以了。
axios分两部分:
第一部分配置请求的网址、参数、http头部信息等等;
实际上这是一个这样的函数 axios(参数),只是这个参数是一个json格式的数据
第二部分是then部分,指的是成功访问后台后,response是指后台返回的数据,这里使用的是lambda表达式。
axios是一个异步发送请求的机制,所谓异步,是指发送请求后就执行后面的代码(上面的代码是指16行后面的代码,如果有的话),后台返回数据的时候,自动执行then这一部分(这一部分又称为回调函数)。
所以有可能发生这样的场景:then这部分迟迟没有执行。
在2.9曾经使用过axios:
import HelloWorld from '@/components/HelloWorld.vue';import axios from "axios";export default{ name:'Home', components:{ HelloWorld }, data(){ return{ username:"中二之魂", message:"正在加载中", html:'<a href="https://www.codessp.cn">学习平台</a>', textValue:'一个值', chapterStudies:[] } ; }, mounted:function(){ let url="https://www.codessp.cn/api/queryStudentsStatistic?chapterId=766&classId=68&courseId=31"; axios({ headers:{ "Content-Type":"application/x-www-form-urlencoded", }, method:"get", url:url, params:'' }) .then((response)=>{ let data=response.data.data; this.chapterStudies=data.chapterStudies; }); }}