小程序,便捷开发 JS 方法。

import config from './config'

function setStorage<T>(key: string, val: T) {
  try {
    uni.setStorageSync(key, val)
  } catch {
    console.log('setStorageSync --- ERROR')
  }
}

function getStorage(key: string) {
  try {
    return uni.getStorageSync(key)
  } catch (e) {
    console.log('getStorageSync --- ERROR')
  }
}

function navTo(url: string, status?: number) {
  if (status == 1) {
    uni.showToast({
      title: '开发中...',
      icon: 'none'
    })
  } else if (status == 2) {
    uni.navigateBack({
      delta: 1,
      animationType: 'pop-out',
      animationDuration: 200,
      fail: () => {
        navTo('/pages/home/index', 3)
      }
    })
  } else if (status == 3) {
    uni.switchTab({
      url: url
    })
  } else if (status == 4) {
    uni.redirectTo({
      url: url
    })
  } else {
    uni.navigateTo({
      url: url,
      animationType: 'pop-in',
      animationDuration: 200
    })
  }
}

type IconType = 'success' | 'error' | 'loading' | 'none'
function showToast(msg: string, duration?: number, icon?: IconType) {
  uni.showToast({
    title: msg,
    duration: duration ?? 2000,
    icon: icon ?? 'none'
  })
}

function showModel(title: string, content: string) {
  return new Promise((resolve, reject) => {
    uni.showModal({
      title,
      content,
      success(res) {
        if (res.confirm) {
          resolve('用户点击确定')
        } else if (res.cancel) {
          reject('用户点击取消')
        }
      }
    })
  })
}

// 选择图片
function chooseImage(count?: number) {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count: count ?? 1,
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success(res) {
        resolve(res.tempFilePaths)
      },
      fail(err) {
        reject(err)
      }
    })
  })
}

// 选择视频
function chooseVideo() {
  return new Promise((resolve, reject) => {
    uni.chooseVideo({
      sourceType: ['album', 'camera'], //从相册选择
      success(res) {
        resolve(res.tempFilePath)
      },
      fail(err) {
        reject(err)
      }
    })
  })
}

// 复制剪贴板
function setClipboardData(data: string) {
  uni.setClipboardData({
    data,
    success: () => {
      console.log('success')
    }
  })
}

// 拨打电话
function makePhoneCall(num: string) {
  uni.makePhoneCall({
    phoneNumber: num, //电话号码
    success: (e) => {
      console.log(e)
    },
    fail: (e) => {
      console.log(e)
    }
  })
}

// 支付
function requestPayment(obj) {
  const params = {
    // 服务提供商
    provider: 'wxpay' as any,
    // 订单数据
    orderInfo: obj.out_trade_no,
    // 统一下单接口返回的 prepay_id 参数值
    package: obj.package,
    // 小程序的appId
    appId: obj.appId,
    // 随机字符
    nonceStr: obj.nonceStr,
    // 时间戳
    timeStamp: obj.timeStamp,
    // 签名
    paySign: obj.paySign,
    // 算法签名
    signType: obj.signType
  }
  return new Promise((resolve, reject) => {
    uni.requestPayment({
      ...params,
      success: (res) => {
        resolve(JSON.stringify(res))
      },
      fail: (err) => {
        reject(JSON.stringify(err))
      }
    })
  })
}

// 获取最小可视高度
function clientHeight(height?: number) {
  return `calc(100vh - ${getStorage('navbarHeight')} - ${getStorage('safeArea')}px - ${getStorage('tabbarHeight')}  - ${getStorage('statusBarHeight')} - ${
    (height ?? 0) * 2 + 'rpx'
  } )`
}

// 除去顶部可视高度
function clientTopHight(height?: number) {
  return `calc(100vh - ${getStorage('navbarHeight')} - ${getStorage('statusBarHeight')} - ${(height ?? 0) * 2 + 'rpx'})`
}

// 上传图片到 OSS
function ossUpload<T>(tempFilePaths: T, key: string): Promise<T> {
  return new Promise((resolve, reject) => {
    uni.showLoading({
      title: '上传中',
      mask: true
    })
    uni.uploadFile({
      url: config.OSS_URL,
      filePath: tempFilePaths[0],
      fileType: 'image',
      name: 'file',
      formData: { key, ...config.OSS_FORM_DATA },
      success: (res) => {
        resolve(res as T)
      },
      fail: (res) => {
        reject(res)
      },
      complete: () => {
        uni.hideLoading()
      }
    })
  })
}

// 获取 OSS 图片路径
function getOssUrl<T>(arr: T): Promise<T> {
  const timestamp = new Date().getTime()
  const fileType: string = arr[0].substring(arr[0].lastIndexOf('.')) || '.jpg'

  const key = `applet/images/${timestamp}${fileType}`
  return new Promise((resolve, reject) => {
    ossUpload<T>(arr, key)
      .then(() => {
        const src = `${config.OSS_URL}/${key}`.toString()
        resolve(src as T)
      })
      .catch((err) => {
        showToast(err)
      })
  })
}

// 判断两个对象值是否相等
function looseEqual(a: object, b: object) {
  if (a === b) {
    //如果是绝对相等就直接返回true
    return true
  }
  //如果不是绝对相等就哦按的他们是否有相同的形状
  const isObjectA = isObject(a)
  const isObjectB = isObject(b)
  if (isObjectA && isObjectB) {
    //两个均是对象
    try {
      const isArrayA = Array.isArray(a)
      const isArrayB = Array.isArray(b)
      if (isArrayA && isArrayB) {
        //如果都是数组
        if (a.length === b.length) {
          //如果长度相等
          return a.every(function (e, i) {
            //用every和递归来比对a数组和b数组的每个元素,并返回
            return looseEqual(e, b[i])
          })
        }
        //长度都不等直接返回false
        return false
      } else if (a instanceof Date && b instanceof Date) {
        //如果是Date 则直接getTime 比较
        return a.getTime() === b.getTime()
      } else if (!isArrayA && !isArrayB) {
        //对象的比较
        //拿到两个对象的key
        const keysA = Object.keys(a)
        const keysB = Object.keys(b)
        if (keysA.length === keysB.length) {
          //如果keys相等
          return keysA.every(function (key) {
            //用every和递归来比对a对象和b对象的每个元素值,并返回
            return looseEqual(a[key], b[key])
          })
        }
        //长度都不等直接返回false
        return false
      } else {
        return false
      }
    } catch (e) {
      return false
    }
  } else if (!isObjectA && !isObjectB) {
    //如果都不是对象则按String来处理
    return String(a) === String(b)
  } else {
    return false
  }
}

// 判断是否为object
function isObject(obj: object) {
  return obj !== null && typeof obj === 'object'
}

// 地图导航
function openLocation(params: { scale: number; longitude: number; latitude: number }) {
  uni.getLocation({
    type: 'gcj02',
    success: (res) => {
      console.log('res', res)
      uni.openLocation(params)
    },
    fail: (err) => {
      console.log(err)
    }
  })
}

// 分享
function shareWx() {
  uni.share({
    provider: 'weixin',
    scene: 'WXSceneSession',
    success: function (res) {
      console.log('success:' + JSON.stringify(res))
    },
    fail: function (err) {
      console.log('fail:' + JSON.stringify(err))
    }
  })
}

// 扫码
function scanCode() {
  return new Promise((resolve, reject) => {
    uni.scanCode({
      success: (res) => {
        resolve(res.result)
        // console.log('条码类型:' + res.scanType)
        // console.log('条码内容:' + res.result)
      },
      fail: () => {
        showToast('扫码失败')
      }
    })
  })
}

// 获取 page
function getPage() {
  const pages = getCurrentPages()
  const perPage = pages[pages.length - 2] as { onLoad; options }
  uni.navigateBack({
    delta: 1,
    success: function () {
      perPage.onLoad(perPage.options)
    },
    fail: () => {
      navTo('/pages/home/index', 3)
    }
  })
}

// 是否免费
function isFree(price: string) {
  if (price != '0.0') return '¥' + price
  return '免费'
}

// 判断对象的值是否为空
function isObjEmpty(obj: object) {
  return Boolean(Object.values(obj).filter((item) => item === '' || item === null).length)
}

// 下载图片
function downImage(url: string) {
  uni.downloadFile({
    url,
    success: (res) => {
      if (res.statusCode != 200) return showToast('下载失败')
      uni.saveImageToPhotosAlbum({
        //保存图片到系统相册。
        filePath: res.tempFilePath, //图片文件路径
        success: () => {
          showToast('图片保存成功')
        },
        fail: () => {
          showToast('图片保存失败')
        }
      })
    }
  })
}

// 对象相同字段快速赋值
function objectSame(obj1: any, obj2: any) {
  Object.keys(obj1).forEach((key) => {
    obj1[key] = obj2[key]
  })
}

export default {
  navTo,
  isFree,
  getPage,
  shareWx,
  scanCode,
  getOssUrl,
  showToast,
  showModel,
  downImage,
  looseEqual,
  objectSame,
  setStorage,
  getStorage,
  isObjEmpty,
  chooseImage,
  chooseVideo,
  clientHeight,
  openLocation,
  makePhoneCall,
  clientTopHight,
  requestPayment,
  setClipboardData
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值