uni-appmuiuni-app

uni-app方法封装

2018-11-14  本文已影响1076人  wppeng

请求数据方法封装

const ApiUrl = '';
export{
  ApiUrl
}
import {
    ApiUrl
} from './env.js';
const ajax = (opt) => {
    opt = opt || {};
    opt.url = opt.url || '';
    opt.data = opt.data || null;
    opt.method = opt.method || 'GET';
    opt.header = opt.header || {
        "Content-Type": "application/json"
    };
    opt.success = opt.success || function () {};

    uni.request({
        url: ApiUrl + opt.url,
        data: opt.data,
        method: opt.method,
        header: opt.header,
        dataType: 'json',
        success: function (res) {
            opt.success(res);
        },
        fail: function () {
            uni.showToast({
                title: '请稍后重试'
            });
        }
    })
}

export {
    ajax
}

文件上传封装

const uploadFile = opt => {
    opt = opt || {};
    opt.url = opt.url || '';
    opt.filePath = opt.filePath || null;//要上传文件资源的路径。   
    opt.name = opt.name || null;//文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 
    
    opt.filePath = opt.filePath || null;
    opt.success = opt.success || function() {};


    uni.uploadFile({
        url: ApiUrl + opt.url,
        filePath:opt.filePath,
        name:opt.name,
        success:function(res){
            opt.success(res);
        },
        fail: function () {
            uni.showToast({
                title: '请稍后重试'
            });
        }

    })
    
}

通用方法

const formatTime = date => {
    date = new Date(date);
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatdate = date => {
    date = new Date(date);
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('.');
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}
/**
 * 根据key查找数据中对应的值
 */
const SearchData = (key, data) => {
    var value = '';
    var i = 0;
    while (i < data.length) {

        if (key == data[i].key) {
            value = data[i].title;
            break;
        } else {
            i++;
            continue;
        }
    }
    return value;
}

/**
 * 根据key查找数据中对应角标
 */
const SearchDataIndex = (key, data) => {
    var value = '';
    var i = 0;
    while (i < data.length) {

        if (key == data[i].key) {
            value = i;
            break;
        } else {
            i++;
            continue;
        }
    }
    return value;
}

module.exports = {
    formatTime,
    formatdate,
    SearchData,
    SearchDataIndex
}

上一篇 下一篇

猜你喜欢

热点阅读