uni-app学习day07-公共js的封装

145 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第30天,点击查看活动详情

开发项目肯定要进行一系列常用的js的封装。比如常用的工具类,vuex状态管理,后台接口工具类,常用的接口封装,请求方式封装等等。

1. 常用的工具类封装-utils.js

用来存放我们常用的工具类,使用时候直接引入即可

  • 时间戳转年月日
// 获取当前时间 (年-月-日 时:分)
export function getTime(time) {
    let date = time ? new Date(time) : new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
    let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    let hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    let minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    return year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
} 
  • 前面加0
const formatNumber = (n) => {
    n = n.toString();
    return n[1] ? n : `0${n}`;
};
  • 数组求差集
export const subSet = function (arr1, arr2) {
    var set1 = new Set(arr1);
    var set2 = new Set(arr2);
    var subset = [];
    for (let item of set1) {
        if (!set2.has(item)) {
            subset.push(item);
        }
    }
    return subset;
};

2. 后台接口封装-api.js

定义一个spi.js,用来放用到的后台接口,这样后台修改接口名的时候,我们可以只修改这个公共的js页面,不至于用到的文件都要修改。减少了工作量。

const BASE_URL_DEFAULT = ['http://192.168.xx.xx:8086/', 'https://xxx'];
const baseURL = BASE_URL_DEFAULT[0]; // 服务器地址

export const getGrade = baseURL + '/schCalendar/v1/getGrade'; // 学年下拉
export const getSemester = baseURL + '/schCalendar/v1/getSemester'; // 学期下拉
export const getClass = baseURL + '/class/v1/getBdClass'; // 班级下拉

3. 公共接口封装-port.js

一些常用的接口,可以进行封装,需要的时候引入,不至于每次用到都要操作一遍,增加了无用的代码量,封装之后,使用很方便,避免了代码的冗余

举个栗子,学年学期接口

// 学年学期下拉
getTermAndSemester(callback) {
    get(getGradeAndSeme).then((res) => {
        if (res && res.length) {
            let index = 0;
            for (let i = 0; i < res.length; i++) {
                res[i].value = res[i].gradeId + '-' + res[i].semeId;
                res[i].text = res[i].gradeName + ' ' + res[i].semeName;
                if (res[i].nowSem) {
                    index = i;
                }
            }
            return callback(res, index);
        }
        if (res.length == 0) return;
        callback(res, 0);
    });
},

4. 请求方式封装-request.js

常用的get,postBody,postParam方法及下载文件的封装

举个栗子,以get为例,post封装类似,可以自己扩展

export function get(url, data = {}, {
    loading = true,
    loadingMsg = '加载中...'
} = {}) {
    const params = {
        method: 'GET',
        url: url,
        data: data,
        header: getHeader(url),
    };

    return handleRequest(params, {
        loading: loading,
        loadingMsg: loadingMsg,
    });
}

function handleRequest(params, {
    loading = true,
    loadingMsg = '加载中...'
} = {}) {
    return new Promise((resolve, reject) => {
        if (loading) {
            if (loadingNum == 0) {
                uni.showLoading({
                    title: loadingMsg || '加载中...'
                });
            }
            loadingNum++;
        }
        uni.request(params).then(([err, res]) => {
            if (err) {
                reject(err);
            }
            const code = res.data.status;
            const message = res.data.message;
            if (code === 203) { // 未登录
                // 跳转到登录页面
                uni.redirectTo({
                        url: '/pages/login/login'
                })
            } else if (code !== 200) {
                uni.showToast({
                        title: message || '服务器出错了,请稍后再试',
                        icon: 'none',
                });
            } else {
                resolve(res.data.result);
            }
        }).catch(err => {
            uni.showToast({
                title: '请检查网络,稍后再试吧',
                icon: 'none',
            });
            reject(err);
        }).finally(() => {
            if (loading) {
                if (loadingNum > 0) {
                        loadingNum--;
                }
                if (loadingNum == 0) {
                        uni.hideLoading();
                }
            }
            })
        })
}