util.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. import simpleCache from './cache.js'
  2. import dateTime from './dateTime.js'
  3. //工具类
  4. let util = {}
  5. //预览图片
  6. // this.$util.preview('http://....png')
  7. // this.$util.preview('../../test.png')
  8. // this.$util.preview(['http://....png', '../../test.png'])
  9. util.preview=async (src)=> {
  10. const urls = typeof src === 'string' ? [src] : src
  11. const filePath = async src => src.match(/^http/) ? src : (await uni.compressImage({ src, quality: 100 }))[1].tempFilePath
  12. for (let i = 0; i < urls.length; i++) {
  13. urls[i] = await filePath(urls[i])
  14. }
  15. uni.previewImage({ urls })
  16. },
  17. //复制
  18. util.copy=content=>{
  19. uni.setClipboardData({ data: content });
  20. }
  21. util.showModal=(content,title='提示')=>{
  22. return new Promise((resolve,reject)=>{
  23. uni.showModal({
  24. title: title,
  25. content: content,
  26. success: (res)=>{
  27. resolve(res)
  28. }
  29. });
  30. })
  31. }
  32. //拨打电话
  33. util.callPhone=phone=>{
  34. uni.showModal({
  35. title: '提示',
  36. content: `确定要拨打电话:${phone}吗?`,
  37. success: function (res) {
  38. if (res.confirm) {
  39. uni.makePhoneCall({
  40. phoneNumber: phone //仅为示例
  41. });
  42. }
  43. }
  44. });
  45. }
  46. //四舍五入保留2位小数(不够位数,则用0替补)
  47. util.keepTwoDecimalFull = num => {
  48. var result = parseFloat(num)
  49. if (isNaN(result)) {
  50. return false
  51. }
  52. result = Math.round(num * 100) / 100
  53. var s_x = result.toString()
  54. var pos_decimal = s_x.indexOf('.')
  55. if (pos_decimal < 0) {
  56. pos_decimal = s_x.length
  57. s_x += '.'
  58. }
  59. while (s_x.length <= pos_decimal + 2) {
  60. s_x += '0'
  61. }
  62. return s_x
  63. }
  64. /**
  65. * 数组去重
  66. * @param {Array} arr 源数组
  67. *
  68. * @return {Array} newArr 去重后的数组
  69. */
  70. util.uniqueArray = (arr)=>{
  71. return [...new Set(arr)]
  72. }
  73. //获取某一个页面上下文 context
  74. util.getPageCtx = (idx = 0) => {
  75. let pages = getCurrentPages()
  76. if (pages.length > 0) {
  77. return pages[pages.length - 1 - idx] || {}
  78. }
  79. return {}
  80. }
  81. //获取当前页面路由
  82. util.getCurrentRoute = () => {
  83. let page = util.getPageCtx()
  84. if (page.route) {
  85. return page.route
  86. }
  87. return ''
  88. }
  89. //回到上一页刷新页面
  90. util.isReloadAndBack = () => {
  91. let prePage=util.getPageCtx(1)
  92. prePage.setData({
  93. "reload":true
  94. })
  95. uni.navigateBack({
  96. delta:1
  97. })
  98. }
  99. //onshow方法通过刷新mescroll数据
  100. util.reload = (mescroll) => {
  101. let page= util.getPageCtx()
  102. if (page.data.reload) {
  103. mescroll.resetUpScroll();
  104. page.data.reload=false
  105. }
  106. }
  107. export default util