哈尔滨洛弘科技
哈尔滨洛弘科技
  • 发布:2023-08-01 11:27
  • 更新:2023-08-01 11:27
  • 阅读:306

uniapp 集成方法,请求类,分页请求,详情请求,数据渲染,验签请求等方式,让你的开发更简单

分类:uni-app

文件存储于根目录下common里,当然大家也可以按照自己的想法存储在不同的位置

本集成方法,共设置三个文件依赖md5加密插件

md5加密插件下载地址

请求接口API模块【api.js】单文件管理接口后期维护成本降低,如更换同一接口地址不用每个文件挨个找了

    export const api=($api)=>{  
    const api={  
        index:'接口具体参数'  
    }  
    return api[$api];  
}

集成方法模块【func.js】
此处可以根据个人需求增加所需的方法,让方法可以在多处使用

/* 输出json */  
function toJson(option) {  

    if (typeof(option) == 'object') {  
        return option;  
    } else if (typeof(option) == 'string') {  
        try {  
            return JSON.parse(option);  
        } catch (e) {  
            return option;  
        }  
    } else {  
        return option;  
    }  

}  

/** 获取列表数据,支持分页加载*/  
function list(othis, param, loading = {  
    is_loading: false,  
    loading_title: ''  
}, k = 'list', p = 'page', i = 'is_list') {  
    if (typeof(loading) == 'object' && loading.is_loading == true) {  
        uni.showLoading({  
            title: loading.loading_title  
        })  
    }  
    othis.request(param.url, param.data).then(res => {  
        uni.hideLoading();  
        othis['is_loading'] = 1;  
        if (res.code == 1) {  
            var data = res.data.data;  
            var page = othis[p];  
            if (data.length < 1) othis[i] = 0;  
            var list = page < 2 ? [] : othis[k];  
            list = list.concat(data);  
            console.log(list);  
            othis[k] = list;  
            uni.stopPullDownRefresh();  
        } else {  
            uni.showModal({  
                title: res.info,  
                icon: 'none'  
            })  
        }  
    })  
}  
/**获取详细数据*/  
function details(othis, param, k = null, loading = {  
    is_loading: false,  
    loading_title: ''  
}) {  
    if (typeof(loading) == 'object' && loading.is_loading == true) {  
        uni.showLoading({  
            title: loading.loading_title  
        })  
    }  
    othis.request(param.url, param.data).then(res => {  
        uni.hideLoading();  
        othis['is_loading'] = 1;  
        if (res.code == 1) {  
            var data = res.data;  
            if (k == null) {  
                for (var i in data) {  
                    othis[i] = data[i];  
                }  
            } else {  
                othis[k] = data;  
            }  
        } else {  
            uni.showModal({  
                title: res.info,  
                icon: 'none'  
            })  
        }  
    })  
}  
/**操作请求*/  
function action(othis, param, type, confirm, loading = {  
    is_loading: true,  
    loading_title: ''  
}) {  
    return new Promise((resolve, reject) => {  
        if (typeof(confirm) == 'object') {  
            uni.showModal({  
                title: confirm.title || '提醒',  
                content: confirm.content || '确定要操作吗?',  
                cancelColor: confirm.cancelColor || '#000',  
                cancelText: confirm.cancelText || '取消',  
                confirmColor: confirm.confirmColor || '#000',  
                confirmText: confirm.confirmText || '确认',  
                success: function(r) {  
                    if (r.confirm) {  
                        do_action(othis, param, type, loading, resolve);  
                    }  
                }  
            })  
        } else {  
            do_action(othis, param, type, loading, resolve);  
        }  
    })  
}  

function do_action(othis, param, type, loading = {  
    is_loading: 1,  
    loading_title: ''  
}, resolve) {  
    if (typeof(loading) == 'object' && loading.is_loading == true) {  
        uni.showLoading({  
            title: loading.loading_title  
        })  
    }  
    othis.request(param.url, param.data).then(res => {  
        uni.hideLoading();  
        othis['is_loading'] = 1;  
        if (res.code == 1) {  
            if (type == undefined || type == '') type = 'back'  
            var action = ['back', 'remind'];  
            if (typeof(type) != 'string' || action.indexOf(type) < 0) {  
                if (typeof(type) != 'object') type = {  
                    type: type  
                };  
                var result = Object.assign(type, param, res)  
                resolve(result);  

            } else {  
                if (type == 'back') {  
                    uni.showToast({  
                        title: res.info,  
                        icon: 'none'  
                    })  
                    setTimeout(function() {  
                        uni.navigateBack();  
                    }, 1500)  
                }  
                if (type == 'remind') {  
                    uni.showToast({  
                        title: res.info,  
                        icon: 'none'  
                    })  
                }  
            }  
        } else {  
            uni.showToast({  
                title: res.info,  
                icon: 'none'  
            })  
        }  
    })  
}  
/* 登录 */  
function login(othis, link = 'login') {  
    // #ifdef H5  
    var pages = getCurrentPages();  
    var curr_page = pages[pages.length - 1].route;  
    uni.navigateTo({  
        url: link  
    })  
    uni.setStorageSync('history_page', pages);  
    // #endif  
    // #ifdef APP-PLUS  

    // #endif  
    // #ifdef MP-WEIXIN  
    return new Promise((resolve, reject) => {  
        if(uni.getStorageSync('access_token').length>10){  
            resolve({code:1,is_login:1})  
            uni.hideLoading()  
            return false;  
        }  
        var code = uni.getStorageSync('login_code');  
        uni.login({  
            success:function(res){  
                if(code.length<10) code=res.code;  
                action(othis, {  
                        url: othis.api('wx_' + link),  
                        data: {  
                            code: code  
                        }  
                    }, 'then').then(res => {  
                        uni.showToast({  
                            title: res.info,  
                            icon: 'none'  
                        })  
                        resolve(res);  
                        if (res.code == 1) {  
                            uni.setStorageSync('access_token', res.data.user_token);  
                        }  
                    })  

            }  
        })  
    })  
    // #endif  
}  
/* h5 页面登录成功跳转 */  
function h5_login(link) {  
    link = link == undefined ? uni.getStorageSync('history_page') : link;  
    uni.navigateTo({  
        url: link  
    })  
}  
module.exports = {  
    toJson: toJson,  
    fetch: fetch,  
    list: list,  
    details: details,  
    action: action,  
    login: login  
}  

请求类库【支持后台验签,让您的数据更安全】

// #ifdef H5  
var server = "/";  
// #endif  
// #ifndef H5  
var server = "请求服务器主域";  
// #endif  
//服务器通过此两个参数验证接口的正确性  
const session_id = '服务器加密session_id';  

const code = '服务器加密code';  
import md5 from '@/js_sdk/js-md5/build/md5.min.js';  
import func from '@/common/func.js';  
import {api} from '@/common/api.js';  
export const _md5=md5;  
export const _func=func;  
export const _api=api  

export const request = (url, data, method) => {  
    return new Promise((resolve, reject) => {  
        //生成验签参数  
        let sign = get_sign(data, code, session_id);  
        var access_token = uni.getStorageSync('access_token');  
        var header = {  
            'content-type': 'application/x-www-form-urlencoded',  
            sign: sign,  
            accesstoken: access_token  
        };  
        var form_data = data || {};  
        console.log(form_data);  
        form_data['at'] = (new Date()).getTime();  
        uni.request({  
            url: server + url,  
            method: method || 'POST',  
            data: form_data,  
            header: header,  
            success: (res) => {  
                resolve(func.toJson(res.data));  
            },  
            fail: (err) => {  
                console.log(err);  
                uni.showToast({  
                    title: '嘤嘤嘤!!!网络出错了哦',  
                    icon: 'none'  
                })  
                reject(err)  
            }  

        })  
    })  
}  
export const uploadFile = (url, file, data) => {  
    return new Promise((resolve, reject) => {  
        let sign = get_sign(data, code, session_id);  
        var access_token = uni.getStorageSync('access_token');  
        var header = {  
            'Content-Type': 'multipart/form-data',  
            sign: sign,  
            accesstoken: access_token  
        };  
        uni.uploadFile({  
            url: server + url,  
            method: "POST",  
            header: header,  
            filePath: file['value'],  
            name: file['field'],  
            success: (res) => {  
                resolve(func.toJson(res.data));  
            },  
            fail: (err) => {  
                uni.showToast({  
                    title: '嘤嘤嘤!!!网络出错了哦',  
                    icon: 'none'  
                })  
                reject(err)  
            }  
        })  
    })  
}  
function get_sign(data, code, session_id) {  
    var str = '';  
    for (var a in data) {  
        str += a + '=' + data[a] + '&';  
    }  
    str +=code;  
    var sign = md5(str);  
    return session_id + '&' + sign;  
}  

main.js 设置以下内容

import { request,uploadFile,_md5,_func,_api } from './common/request.js';  
Vue.prototype.request= request;  
Vue.prototype.uploadFile=uploadFile;  
Vue.prototype.md5=_md5;  
Vue.prototype.func=_func;  
Vue.prototype.api=_api;

这样即可在其他页面调用

请求服务器分页数据仅需要简单代码即可完成

    export default {  

        data() {  
            return {  
                page:1,  
                list:[],  
                is_list:1  
            }  
        },  
         onLoad() {  
        this.func.list(this,this.api('index'),{page:this.page})  
        },  
        methods: {    
        }  
    }  

其他方法也是如此请求带弹窗的请求如下

this.func.action(this,  
                {url:this.api('test'),  
                data:{abc:'abc'}},'then',{title:'确认提交',content:'提交楼'}).then(res=>{  
                    console.log(res);  
                })

请求详细数据如下

//接收参数abc直接渲染即可  
this.func.details(this,{id:1},'abc');

登录代码,方便开发,也方便直接验证登录操作,如已经登录会直接执行then内方法

this.func.login(this).then(res=>{  
                    console.log(res);  
                })
0 关注 分享

要回复文章请先登录注册