Nine

人生三重境界:昨夜西风凋碧树,独上高楼,望尽天涯路。 衣带渐宽终不悔,为伊消得人憔悴。 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。

uni-app接口简单封装(简洁版)

封装uni.request()接口的 util/api.js文件:

// 二次封装请求接口
const BASE_URL = 'http://localhost:8082'
 
export const myRequest = (options) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: BASE_URL + options.url,
            method: options.method || 'GET',
            data: options.data || {},
            success: (res) => {
                if(res.data.status !== 0){
                    return uni.showToast()({
                        title: '获取数据失败'
                    })
                }
                resolve(res)
            },
            fail: (err) => {
                uni.showToast()({
                    title: '请求接口失败'
                })
                reject(err)
            }
        })
    })
}

然后在main.js文件内进行导入和全局挂载

import { myRequest } from './util/api.js'
 
Vue.prototype.$myRequest = myRequest

页面使用 (通过这个$myRequest进行访问接口,并获取数据)

async getData(){
    const res = await this.$myRequest({
        url: '/api/test'
    })
    conso le.log(res.data)
}

 

posted on 2020-09-22 14:46  耳机里听雨  阅读(349)  评论(0)    收藏  举报