工具

uniapp 使用mock数据方式总结

2019-12-25  本文已影响0人  janezhang

1.2019.12.25
uniapp使用了vue, 那开发环境 如何mockJS? 分为3个步骤
--- 通过封装uniapp的请求函数,然后劫持uniapp的请求。其中用到了装饰者函数。可以做到函数职责单一原则,不需要修改请求函数。
1.封装uniapp request: 如下:

function fetch({ 
    url,
    method = 'GET',
    data,
    showLoading = false,
    header = {
        'content-type': 'application/json'
    },
}) {
    if (showLoading) {
        uni.showLoading({
            mask: true
        });
    }
    if (method.toLowerCase() == 'post') {
        header['content-type'] = 'application/x-www-form-urlencoded'
    }
    return new Promise((resolve, reject) => {
        uni.request({
            url, //仅为示例,并非真实接口地址。
            header,
            data: {
                ...data,
                openid: uni.getStorageSync('openid') || '',
                language: uni.getStorageSync('language') || 'en'
            },
            method,
            success: (res) => {
                console.log(url, data, method, res);
                if (res.statusCode == 200) {
                    // if (res.data.status != 0) {
                    //  uni.showToast({
                    //      icon: "none",
                    //      title: res.data.msg,
                    //      duration: 2000
                    //  })
                    // }
                    resolve(res.data)
                    if (showLoading) {
                        uni.hideLoading();
                    }
                } else {
                    reject(res)
                }
            },
            error(err) {
                reject(err)
                uni.hideLoading();
            }
        });
    })

}

2.装饰者拦截请求:

Function.prototype.before = function( fn ){
    var self = this;
    return function(){
        let f = fn.apply( this, arguments );
        if( f ){
            console.log( arguments );
            let opt = arguments[0];
            let index = opt.url.lastIndexOf('/');
            var name = opt.url.substring(index+1);
            console.log(name);
            //这里mock返回, promise函数
            var url =` http://localhost:8080/${name}.json`;
            return mock(url);
        }
        return self.apply( this, arguments );
 
    }
}
function mock( url ){
    return uni.request({
        url: url, //仅为示例,并非真实接口地址。
        data: {
            text: new Date(),
        },
        method: 'GET',
        header: {
            'custom-header': 'hello' //自定义请求头信息
        }
    }).then( function( data ){
        return data[1].data;
    })
}
  1. 使用方式:
//若是开发环境则 是调用拦截,否则,将原来fetch原封不动,给到Vue.prototype.$fetch .
if( process.env && process.env.NODE_ENV === 'development'){
      // 这里调用拦截之前封装的fetch请求 fetch.before。
    Vue.prototype.$fetch = fetch.before( function(){
        return true;
    })
}else{
    Vue.prototype.$fetch = fetch
}
上一篇 下一篇

猜你喜欢

热点阅读