1.安装axios
npm install --save axios vue-axios
2.在main.js中导入axios
import Vue from 'vue'
import App from './App'
import router from '../src/router/router'
import axios from 'axios'
// Vue.use(axios); //使用此种方法引入会出现 not defind
Vue.component('chart', ECharts)
Vue.config.productionTip = false;
Vue.prototype.$axios = axios;
3.get方法封装
export function get(url,params,serviceSuccessCallBack, serviceErrorCallBack) {
return new Promise((resolve, reject) =>{
axios.get(url, {
params : params
}).then(res => {
//请求成功
if(res.status == 200) {
if (serviceSuccessCallBack == null) {
console.log('serviceSuccessCallback');
} else {
serviceSuccessCallBack(res);
console.log(res);
}
}else{
serviceSuccessCallBack(res);
}
resolve(res.data);
}).catch(err =>{
//请求失败
reject(err.data);
serviceErrorCallBack(err);
})
});
}
- post方法封装
export function post(url, data ,serviceSuccessCallBack, serviceErrorCallBack) {
let header ={};
header ={
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json;charset=UTF-8',
}
const options = {
method: 'POST',
headers: header,
data: data,
url:url
};
return new Promise((resolve,reject) => {
axios(options).then(res => {
if(res.status == 200) {
if (serviceSuccessCallBack == null) {
console.log('serviceSuccessCallback');
} else {
serviceSuccessCallBack(res);
console.log(res);
}
}else{
serviceSuccessCallBack(res);
}
resolve(res);
})
.catch(function (err) {
reject(err);
serviceErrorCallBack(err);
})
})
}
5.此处对请求使用service再次封装
import {appConstant} from '../common/appConstant.js'
import {methodSingleGoods} from '../common/appConstant.js'
import {post} from '../common/httpAxios.js'
import {get} from "../common/httpAxios.js";
// post 方法
export function getSingleGoods(data ,successCallBack, errorCallBack) {
// appConstant.methodSingleGoods(): 为URL地址
// data:传递后台参数
post(appConstant.methodSingleGoods(), data , successCallBack ,errorCallBack);
}
//get方法
export function getAddress(params,successCallBack, errorCallBack) {
//params: 地址栏需要的参数
let url = '/api/';
getHttp(url, params ,successCallBack ,errorCallBack);
}
6.post方法使用
import {getSingleGoods} from '../../service/personalService.js'
export default {
data() {
return { }
},
created(){
const data = {code': ‘1231232’};
getSingleGoods(data, singleSucessBack, singleErrorBack);
function singleSucessBack(res) {
//请求成功
console.log(res);
}
function singleErrorBack(error) {
//请求失败
console.log(error)
}
}
}
7.get方法使用示例
import {getAddress} from '../../service/personalService.js'
export default {
data() {
return { }
},
created(){
let params = {
'address':'北京市朝阳区工体北路',
'ak':'百度地图的appKey',
'output':'json',
};
getAddress(params,sucessAddressCallBack, errorAddressCallBack);
function sucessAddressCallBack(res) {
//请求成功
console.log(res);
};
function errorAddressCallBack(err) {
//请求失败
console.log(err);
}
}
}