前端开发中封装的一些常见方法

金额格式化

在开发中涉及到的金额,需要对其进行金额格式化,如123456.23需要转化为123,456.23,就需要我们封装方法了:
我们需要对每一项数字的位置进行判断,此时用字符串比较方便,又数组和字符串的结构相似,数组的一些方法比较灵活,故使用数组的方法进行处理。
主要利用了数组的reverse()方法和reduce(fn,data)方法,reverse()方法主要是对数组进行倒序排列,从后往前进行处理;reduce(fn,data)方法的参数有两个:

  1. fn为一个函数,它有四个参数res,item,index,arr,其中res为上一次处理的结果,可以传递参数;item为当前循环项,index为当前循环项的索引,arr为原始数组;
  2. data为初始化数据,如果传入了则为res的默认值;
/**
 * 格式化金额
 * @param {金额} amount 
 */
const formatAmount = (amount) => {
    if (!amount) {
        return '0.00';
    }
    //金额从后往前,如3384=>4833
    const amountA = Array.from(`${amount}`).reverse();
    let res = amountA.reduce((res, item, index, arr) => {
        let temp = `${item}${res}`;
        //在前面追加,
        temp = (((index + 1) % 3 == 0 && index + 1 < arr.length) ? ',' : '') + temp;
        return temp;
    });
    return `${res}.00`;
    /* amountA.splice(); */
}

判断函数是否为异步函数

涉及到原型概念,对象的constructor等于对象原型的constructor等于函数本身;
function Fn(){a=1;console.log(a)}; a = new Fn();
a.__proto__==Fn.prototype
a.constructor 等于a.__proto__.contructor等于Fn.prototype.constructor() 等于Fn

/**
 * 判断函数是否为异步函数
 * @param {函数} fun 
 */
const judgeAsync = (fun) => {
    const AsyncFunction = (async () => { }).constructor;
    return fun instanceof AsyncFunction;
}

获取微信签名

import wx from 'weixin-js-sdk'
/**
 * 获取微信签名
 * @param {openId} openId 
 * @param {当前前端页面的url地址(不带参数)} url 
 */
const getWechatSign = ({ openId = 123456, url = location.href.split('#')[0], jsApiList, action }) => {
    const data = { openId, url };
    request({
        APIName: 'wxgetSign',
        data: { data }
    }).then(res => {
        const { nonceStr, signature, timestamp } = res;
        wx.config({
            debug: false,//开启调试模式
            appId: process.env.VUE_APP_APPID,
            timestamp,
            nonceStr,
            signature,
            jsApiList
        });
        wx.error((res) => {
            console.log(res);
        });
        wx.ready(() => {
            wx.checkJsApi({
                jsApiList: ['chooseWXPay'],
                success(res) {
                    console.log("checkd api:", res);
                },
                fail(err) {
                    console.log("check api fail:", err);
                }
            });

            typeof action === 'function' && action();
        });

    }, reject => {
        console.log(reject);
    });
};

其中request为自定义的方法,如下:

import axios from 'axios';

import { Base64 } from 'js-base64';
import api from '@/common/api/index.js';
import { Dialog } from 'vant';
/**
 * 返回一个请求
 * @param {请求的数据} paramsData
 */
const request = (paramsData) => {
    return new Promise((resolve, reject) => {
        let { method = 'POST', APIName, params, data, isBase64 = true,headers, /* telNo, userToken, encryption */successTips, failTips } = paramsData || {};
        if (isBase64) {
            //base64加密
            data = getBase64Data(data);
        }

        axios({
            method,
            url: `${api[APIName]}`,
            ...method === 'GET' ? { params } : { data },
            ...headers ? {headers} : {},
            //headers: getToken({ APIName, data, userName: telNo, userToken, encryption }),
            timeout: 60000
        }).then(response => {
            const { success, msg, obj = {} } = response.data;
            if (success) {
                resolve(obj);
                if (successTips) {
                    Dialog.alert({ title: '提示信息', message: successTips.message });
                }
            } else {
                reject(msg);
                if (failTips) {
                    Dialog.alert({ title: '提示信息', message: failTips});
                } else {
                    if(msg.indexOf("交易流水号已失效")>=0){
                        Dialog.alert({ title: '提示信息', message: "您的订单已过期请重新投保" });
                    }else{
                        Dialog.alert({ title: '提示信息', message: msg });
                    }   
                }

            }

        }).catch(error => {
            if (failTips) {
                console.log(failTips);
            } else {
                Dialog.alert({ title: '提示信息', message: error });
            }
            reject(error);
        });
    });
}

const getBase64Data = (data) => {
    if (typeof data !== 'string') {
        data = JSON.stringify(data);
    }
    return Base64.encode(data);
};

vue组件下调用微信签名方法:

//vue组件下调用
 this.request({
        APIName: "xcxPaymentUrl",
        data: { data },
        isBase64: false,
      })
        .then((obj) => {
          this.$toast.clear();
          const {
            timeStamp: timestamp,
            package: p,
            paySign,
            signType,
            nonceStr,
            appId,
          } = JSON.parse(obj.payInfo || "{}");
          //真正的支付操作
          wx.chooseWXPay({
            appId,
            timestamp,
            nonceStr,
            package: p,
            signType,
            paySign,
            success() {
              //支付成功后跳转到 非车险业务 的支付成功页面
              window.location.href = api.payNotCarSuccess;
            },
            fail() {},
            cancel() {
              //todo
              if (this.isRealNamePay) {
                //实名认证的话
                this.$router.go(-2);
              } else {
                this.$router.go(-1);
              }
            },
          });
        })
        .catch(() => {
          this.$toast.clear();
        });

持续更新中~~

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值