封装http并挂载到全局

https://www.bilibili.com/video/BV1BJ411W7pX?p=32

具体使用:https://blog.csdn.net/weixin_44763569/article/details/107267124

1)封装前的接口写法

2)封装后的写法

async, await用法:

普通用法:

integral() {
    this.$myRequest({
        url: '/mall/user-integral',
    }).then(res => {
        this.integrall = res.data.integral
    })
}

3)api.js封装:

 1 // 全局请求路径,也就是后端的请求基准路径
 2 const BASE_URL = 'http://192.168.31.39:8899/'
 3 // 同时发送异步代码的次数,防止一次点击中有多次请求,用于处理
 4 let ajaxTimes=0;
 5 // 封装请求方法,并向外暴露该方法
 6 export const myHttp = (options)=>{
 7     // 解构请求头参数
 8     let header = {...options.header};
 9     // 当前请求不是登录时请求,在header中加上后端返回的token
10     if(options.url != 'login'){
11         header["client-identity"] = uni.getStorageSync('session_id');
12     }
13     ajaxTimes++;
14     // 显示加载中 效果
15     uni.showLoading({
16         title: "加载中",
17         mask: true,
18     });
19     return new Promise((resolve,reject)=>{
20         uni.request({
21             url:BASE_URL+options.url,
22             method: options.method || 'POST',
23             data: options.data || {},
24             header,
25             success: (res)=>{
26                 resolve(res)
27             },
28             fail: (err)=>{
29                 reject(err)
30             },
31             // 完成之后关闭加载效果
32             complete:()=>{
33                 ajaxTimes--;
34                 if(ajaxTimes===0){
35                     //  关闭正在等待的图标
36                     uni.hideLoading();
37                 }
38             }
39         })
40     })
41 }

4)main.js调用:

import { myHttp } from './util/api.js';
Vue.prototype.$http = myHttp;

 https://blog.csdn.net/renxiaoxing55/article/details/112647858

原文地址:https://www.cnblogs.com/guwufeiyang/p/14914050.html