使用uniapp开发小程序中封装请求并使用promise处理

使用uniapp开发小程序中封装请求并使用promise处理

1.在src中创建一个工具文件夹utils,在utils下创建请求封装文件request.js:
在这里插入图片描述
2.在request.js中封装自己的小程序请求,如:

export default function(config) {
    // 从参数中解构 baseURL参数
    const { baseURL } = config;

    // 真正的vue插件
    return function(Vue) {

        // 添加全局方法
        Vue.prototype.http = async function(params) {
            // 请求参数
            // console.log(params);

            const { url, method, data } = params;

            // 真正的请求发出
            const res = await uni.request({
                url: baseURL + '' + url,
                method,
                data,
            });

            return res[1].data;
        };
    };
}

这里由于小程序中promise返回的是一个数组,数组索引为0的是错误信息,为null则没有错误,数组索引为1的项的data则是我们想要获得的放回数据,所以直接return出去

3.将我们自己封装的request请求引入到main.js中,并使用插件挂载的方式挂载

import Vue from 'vue';
import App from './App';

// 导入封装的request接口
import request from '@/utils/request';

Vue.config.productionTip = false;

App.mpType = 'app';

// 插件
const plugin = request({
    baseURL: 'https://www.uinav.com',
});
Vue.use(plugin);

const app = new Vue({
    ...App,
});
app.$mount();

4.我们在main.js中将请求http挂载到了vue的原型上,所以页面中可以直接通过this.http调用,如:

 async getFloorList() {
      const res = await this.http({
        url: "/api/public/v1/home/floordata",
        method: "get"
      });
      // console.log(res);
      this.floorList = res.message;
    }
  },
async getNavList() {
      const res = await this.http({
        url: "/api/public/v1/home/catitems",
        method: "get"
      });

      this.categoryList = res.message;
    },

猜你喜欢

转载自blog.csdn.net/weixin_47346395/article/details/107412579