在项目中都须要与后台进行数据交互,最经常使用的库就是axios。
为了更方便的在项目中的使用,那就本身动手开发一个基于项目的请求插件。
从接口配置、简单调用、少许操做、Promise等需求点出发,最后写出这个插件。
欢迎 点赞、收藏、评论、建议
欢迎 点赞、收藏、评论、建议
欢迎 点赞、收藏、评论、建议 (重要的事情说三遍)vue
npm install axios-vue-http
复制代码
import Http from 'axios-vue-http'
Vue.use(Http);
复制代码
地址:协议://域名.接口路径[/url参数]github
大部分请求只须要同域名,因此域名默认不须要配置。
接口路径以实际开发为准
url参数分两类:
一类是get请求,如/?a=1&b=2
一类是相似路由参数,如/delUser/11,中的11npm
传入data为Object类型,插件会根据Method自动放置
如 data = {a:1,b:2}, method: get时自动生成 url/?a=1&b=2axios
返回数据格式是JSON。api
import Http from 'axios-vue-http'
Vue.use(Http);
const apiList = [
{apiName: 'getTest', method: 'GET', url: 'api/test'},
{apiName: 'postTest', method: 'POST', url: 'api/test'},
{apiName: 'delTest', method: 'DELETE', url: 'api/test'},
{apiName: 'putTest', method: 'PUT', url: 'api/test'},
]
function success({res, resolve, reject}) {
// 接口请求成功处理 (status === 200)
// ...处理数据,
// example res.data = {code: 200, data: {list: [], page: 1}, msg: '获取成功'}
let { data } = res;
if(data.code = 200){
resolve(data.data);
}
// example res.data = {code: -10001, msg: '获取失败'}
let { data } = res;
if(data.code < 0){
app.$message.error(data.msg);
reject(new Error(data.msg));
}
// 使用resolve(数据)向下传递
// 使用reject(err)向下传递
}
function fail({res, reject}) {
// 接口请求失败处理(status !== 200)
// 使用reject(err)向下传递
}
function genHeader() {
let headers = {
token: localStorage.getItem('token') || undefined,
}
return { headers };
}
const app = new Vue({
beforeMount() {
this.$http.addApiList(apiList); //设置接口列表
this.$http.requestInterceptors(genHeader); //设置请求拦截器,添加headers token
this.$http.setSuccess(success); //设置请求成功回调
this.$http.setFail(fail); //设置请求失败回调
},
render: h => h(App),
});
app.$mount('#app');
复制代码
request(apiName, data, param);bash
参数 | 描述 |
---|---|
apiName | 接口请求名称 |
data | 接口发送数据 post中使用data, get中会拼到url中 |
param | url参数,例:request('getTest',{a:1}, '/123') ===> xxx.xxx.xxx/api/test/12… |
// 在页面中使用
methods: {
async getFetach(){
try {
const res = await this.$http.request('postTest', {p1: 1});
}catch(err) {
console.error('请求失败:', err)
}
},
}
复制代码