安装axios:
- -
目录结构:
红框部分是接口文件:
appApi.js是存放接口的文件
import Vue from 'vue'
import axios from 'axios' export default {show_category: function () {return axios.post('/point-api-show_category' );},get_product: function (data) {return axios.post('/point-api-get_product' ,data);}
}
apiServer.js是设置vue的属性API的:
import Vue from 'vue'
import API from './API/appApi' Vue.prototype.API = API;
在main.js里引入axios和apiServer.js
import ProtoTypeAPI from './network/apiServer'
import axios from 'axios'
new Vue({el: '#app' ,router,store,axios,template: '<App/>' ,components: { App },methods: {setSessionStorage:function (data) { for (let key in data){sessionStorage[key] = data[key];}},setLocalStorage: function (data) { for (let key in data){localStorage[key] = data[key];}}}
})
组件里调用接口:
get_product : function (name,cate_id) {this .API.get_product({name : name,cate_id : cate_id}).then ((response) => {console .dir(response);}, (response) => {mui.toast('网络错误' );}) ;}
import Vue from 'vue'
import axios from 'axios'
import GLOBAL_CONFIG from './config'
const CONFIG = GLOBAL_CONFIG['GLOBAL_CONFIG' ];axios.defaults.baseURL = CONFIG['API_HOST' ];
axios.interceptors.request.use (function (config) { let TOKEN=localStorage.token;if (TOKEN){ config.headers['X-ODAPI-Authorization' ] = TOKEN;}return config;},function (error) {return Promise.reject(error);
});
axios.interceptors.response.use (function (response) {if (response['status' ] == 200 ){if (response['data' ]['error_code' ] == 0 ){return response['data' ]['data' ];}else { if (response['data' ].hasOwnProperty('erron' )){mui.toast(response['data' ]['erron' ]);}return false ;} }else {mui.toast('网络错误!' );}},function (error) {return Promise.reject(error);
})
配置文件config.js
export default { GLOBAL_CONFIG :{'API_HOST' : '接口地址' ,'base64Header' : 'data:image/png;base64,' ,'dataImage' :'data:image' ,'db' :'odoo3' , }
}