一、安装axios
$ cnpm i axios -S
二、配置axios
创建文件src/api/index.js
写入配置
import Vue from 'vue'
import Axios from 'axios'
// 这里的配置了POST、GET、PUT、DELETE方法。并且自动将JSON格式数据转为URL拼接的方式
// 同时配置了跨域,不需要的话将withCredentials设置为false即可
// 并且设置了默认头部地址为:http://127.0.0.1:8000/,这样调用的时候只需写访问方法即可
Vue.use(Axios)
let http = Axios.create({
baseURL: 'http://127.0.0.1:8000/',
withCredentials: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
},
transformRequest: [function (data) {
let newData = '';
for (let k in data) {
if (data.prototype.hasOwnProperty.call(k) === true) {
newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&';
}
}
return newData;
}]
});
function apiAxios(method, url, params, response) {
http({
method: method,
url: url,
data: method === 'POST' || method === 'PUT' ? params : null,
params: method === 'GET' || method === 'DELETE' ? params : null,
}).then(function (res) {
response(res);
}).catch(function (err) {
response(err);
})
}
export default {
get: function (url, params, response) {
return apiAxios('GET', url, params, response)
},
post: function (url, params, response) {
return apiAxios('POST', url, params, response)
},
put: function (url, params, response) {
return apiAxios('PUT', url, params, response)
},
delete: function (url, params, response) {
return apiAxios('DELETE', url, params, response)
}
}
三、使用axios
在 mian.js 中导入
import Api from './api/index.js';
Vue.prototype.$api = Api;
使用
getDevices() {
this.$api.get('treeLog/devices/', {
staff_id: this.staffId,
}, response => {
if(response.data.status == 1){
console.log(response.data.result);// 成功数据
}else {
console.log(response.msg);// 失败信息
}
})
}