一、环境安装
1、axios的安装
进入到对应工程目录执行:
npm install axios
2、启动测试数据的API
测试项目地址:https://github.com/ShenJianPing0307/VueTestAPI
二、使用axios
使用文档:https://github.com/axios/axios
发送get请求实例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> {{ userInfo }} </div> <script src="node_modules/vue/dist/vue.js"></script> <script src="node_modules/axios/dist/axios.js"></script> <script> new Vue({ el:'#app', data:{ userInfo:[] }, created(){ //发送get请求获取API数据 axios.get(' http://127.0.0.1:8000/api/userdata/') .then((response)=>{ // handle success console.log(this); //使用箭头函数this才是Vue实例对象,否则是window对象 this.userInfo=response.data; console.log(response.data); }) .catch((error)=>{ // handle error console.log(error); }) .finally(()=>{ // always executed }); } }) </script> </body> </html>
注意:在axios中处理逻辑中使用箭头函数,否则this就是window对象
返回值response中包含的信息:
axios.get(' http://127.0.0.1:8000/api/userdata/') .then(function (response) { console.log(response.data);//请求的数组数据 console.log(response.status);//200 console.log(response.statusText);//ok console.log(response.headers);//content-type: "text/html; charset=utf-8" console.log(response.config);//所有的配置信息包括url,headers,method等 });