一、环境安装
1、axios的安装
进入到对应工程目录执行:
npm install axios
2、启动测试数据的API
测试项目地址:https://github.com/ShenJianPing0307/VueTestAPI
二、使用axios
使用文档:https://github.com/axios/axios
1、发送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数据,自行将json数据反序列化 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>
2、发送post请求实例
addItem(context, payload) { //发送的直接是json数据,如果返回的是json数据直接就被反序列化了
axios.post('http://127.0.0.1:8000/api/addUser/',payload.data) .then(response=>{ if (response.data.state) { payload.successfunc(); //执行保存成功提示函数 } else { payload.failturefunc(); //执行保存失败提示函数 } //保存返回的数据状态,mutation修改state状态,所以传给mutation处理 context.commit('ADDITEM', response.data); }) },
// 1、Content-Type: application/json import axios from 'axios' let data = {"id":"1","name":"aa"}; axios.post('http://127.0.0.1:8000/api/addUser/",data) .then(res=>{ console.log('res=>',res); }) // 2、Content-Type: multipart/form-data import axios from 'axios' let data = new FormData(); data.append('id','1'); data.append('name','aa'); axios.post('http://127.0.0.1:8000/api/addUser/",data) .then(res=>{ console.log('res=>',res); }) //Content-Type: application/x-www-form-urlencoded import axios from 'axios' import qs from 'qs' let data = {"id":"1","name":"aa"}; axios.post('http://127.0.0.1:8000/api/addUser/",qs.stringify({ data })) .then(res=>{ console.log('res=>',res); })
注意:在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等 });