utils.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. import clone from './clone.js'
  2. /**
  3. * @desc 函数防抖
  4. * @param func 函数
  5. * @param wait 延迟执行毫秒数
  6. * @param immediate true 表立即执行,false 表非立即执行
  7. */
  8. export let debounce = (func, wait, immediate) => {
  9. let timeout;
  10. return function () {
  11. let context = this;
  12. let args = arguments;
  13. if (timeout) clearTimeout(timeout);
  14. if (immediate) {
  15. let callNow = !timeout;
  16. timeout = setTimeout(() => {
  17. timeout = null;
  18. }, wait);
  19. if (callNow) func.apply(context, args);
  20. } else {
  21. timeout = setTimeout(() => {
  22. func.apply(context, args);
  23. }, wait);
  24. }
  25. };
  26. };
  27. export const goHome = () => {
  28. uni.redirectTo({
  29. url: '/page/index/index'
  30. })
  31. return
  32. }
  33. /**
  34. * @desc 函数节流
  35. * @param func 函数
  36. * @param delay 毫秒数
  37. */
  38. export let throttle = (func, delay) => {
  39. let timeout;
  40. return function () {
  41. let args = arguments;
  42. if (!timeout) {
  43. timeout = setTimeout(() => {
  44. func.apply(this, args);
  45. timeout = null;
  46. }, delay);
  47. }
  48. };
  49. };
  50. /**
  51. * 函数节流
  52. * @param fn
  53. * @param interval
  54. * @returns {Function}
  55. * @constructor
  56. */
  57. let startThrottleTimer = true; // 是否第一次执行 第一次点击时立即执行一次,后续不再立即执行
  58. let isThrottleTimer = false; // 第一次是否执行
  59. let ThrottleTimer = true; // 节流函数开关
  60. // 节流函数
  61. export let Throttle = function (fn, delay) {
  62. var arg = Array.from(arguments).splice(2);
  63. if (ThrottleTimer) {
  64. if (startThrottleTimer) {
  65. fn.apply(this, arg);
  66. startThrottleTimer = false;
  67. }
  68. ThrottleTimer = false;
  69. setTimeout(() => {
  70. ThrottleTimer = true;
  71. if (isThrottleTimer) {
  72. fn.apply(this, arg);
  73. }
  74. startThrottleTimer = true;
  75. isThrottleTimer = !startThrottleTimer;
  76. }, delay);
  77. }
  78. };
  79. // 校验手机号
  80. export function phoneValidate(phone) {
  81. const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
  82. return reg.test(phone)
  83. }
  84. // 校验+86手机号 \ 座机电话
  85. export function is86Phone(phone) {
  86. const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
  87. if (reg.test(phone)) {
  88. return true
  89. }
  90. const str2 = phone.substring(0, 2)
  91. if (str2 == '86') {
  92. const str3 = phone.substring(2, phone.length - 1)
  93. if (reg.test(str3)) {
  94. return true
  95. }
  96. }
  97. const regMob = /^((0\d{2,3})-)?(\d{7,8})$/
  98. if (regMob.test(phone)) {
  99. return true
  100. }
  101. return false
  102. }
  103. // 复制文本
  104. export function copy(data, msg) {
  105. uni.setClipboardData({
  106. data: data,
  107. success: () => {
  108. uni.showToast({
  109. title: msg || '复制成功',
  110. icon: 'none',
  111. mask: true
  112. })
  113. }, fail: () => {
  114. // uni.showToast({
  115. // title: '复制失败',
  116. // icon: 'none',
  117. // mask: true
  118. // })
  119. copyFallback(data)
  120. }
  121. })
  122. }
  123. function copyFallback(text) {
  124. // 创建临时textarea元素
  125. const textarea = document.createElement('textarea');
  126. textarea.value = text;
  127. textarea.style.position = 'fixed'; // 防止页面滚动
  128. document.body.appendChild(textarea);
  129. textarea.select();
  130. try {
  131. // 执行复制命令
  132. const successful = document.execCommand('copy');
  133. if (successful) {
  134. uni.showToast({title: '复制成功', icon: 'none'});
  135. } else {
  136. throw new Error('复制失败');
  137. }
  138. } catch (err) {
  139. console.error('复制失败:', err);
  140. uni.showToast({title: '复制失败,请手动复制', icon: 'none'});
  141. // 提示用户手动复制
  142. prompt('请手动复制以下内容', text);
  143. } finally {
  144. document.body.removeChild(textarea);
  145. }
  146. }
  147. // 拨打电话
  148. export function callPhone(phone) {
  149. uni.makePhoneCall({
  150. phoneNumber: phone
  151. })
  152. }
  153. // 拆分字符串--汉字 | 数字
  154. export function splitStr(str) {
  155. if (!str) {
  156. return
  157. }
  158. let show_text = str
  159. const arr = Array.from(new Set(show_text.match(/\d+(.\d+)?/g)))
  160. let replace_text = arr.map(item => {
  161. if (item.length >= 8 && item.length <= 11) {
  162. return item
  163. }
  164. })
  165. for (var i = 0; i < replace_text.length; i++) {
  166. var replaceString = '**' + replace_text[i] + "**"
  167. show_text = show_text.replace(RegExp(replace_text[i]), replaceString)
  168. }
  169. return show_text.split('**')
  170. }
  171. // 预览pdf
  172. export function exportPDF(pdfUrl) {
  173. // #ifdef H5
  174. window.open(
  175. pdfUrl
  176. )
  177. // #endif
  178. // 微信下载文件需要在微信公众平台>开发>开发管理>服务器域名>downloadFile合法域名>配置白名单域名
  179. // #ifdef MP-WEIXIN
  180. uni.downloadFile({
  181. url: pdfUrl,
  182. success: res => {
  183. console.log(res)
  184. if (res.statusCode === 200) {
  185. // 预览pdf文件
  186. uni.openDocument({
  187. filePath: res.tempFilePath,
  188. showMenu: true, // 右上角菜单,可以进行分享保存pdf
  189. success: function (file) {
  190. console.log("file-success", file)
  191. }
  192. })
  193. }
  194. }
  195. })
  196. // #endif
  197. // #ifdef APP-PLUS
  198. uni.downloadFile({
  199. url: pdfUrl,
  200. success: res => {
  201. console.log(res)
  202. if (res.statusCode === 200) {
  203. // 保存pdf文件至手机,一般安卓端存储路径为:手机存储/dcim/camera文件夹下
  204. uni.showLoading({
  205. title: '请稍等...'
  206. })
  207. setTimeout(function () {
  208. uni.hideLoading()
  209. // 预览pdf文件
  210. uni.openDocument({
  211. filePath: res.tempFilePath,
  212. showMenu: true,
  213. success: function (file) {
  214. console.log("file-success", file)
  215. }
  216. })
  217. }, 1000)
  218. }
  219. }
  220. })
  221. // #endif
  222. }
  223. /**
  224. * 抹除api请求的对象的null和undefined
  225. */
  226. export const wipeNulish = (obj) => {
  227. obj = Object(obj) // 不是对象类型就转成对象类型
  228. obj = clone(obj, true) // 不改变原来的值
  229. Object.keys(obj)
  230. .forEach((key) => {
  231. // 删除null和undefined
  232. obj[key] == null && delete obj[key]
  233. if (
  234. typeof obj[key] === 'object' &&
  235. Object.prototype.toString.call(obj) === '[object Object]'
  236. ) {
  237. // 不对Array或Date或RegExp这样的对象处理
  238. // 递归删除
  239. wipeNulish(obj[key])
  240. }
  241. })
  242. return obj
  243. }
  244. // 调用历史栈页面方法
  245. export function pageInit(obj = {}) {
  246. if (!obj.route || !obj.funName) {
  247. return
  248. }
  249. return new Promise(resolve => {
  250. let params = {
  251. route: obj.route,
  252. funName: obj.funName
  253. }
  254. const pages = getCurrentPages()
  255. const listPage = pages.find(item => item.route === params.route)
  256. if (listPage) {
  257. console.log(listPage)
  258. const fun = listPage.$vm[params.funName]
  259. fun && fun()
  260. setTimeout(_ => {
  261. resolve()
  262. }, 300)
  263. } else {
  264. resolve()
  265. }
  266. })
  267. }
  268. // 获取url参数--普通
  269. export const getUrlParamsNormal = (param) => {
  270. let query = ''
  271. let hash = window.location.hash
  272. const index = hash.indexOf('#')
  273. query = hash.substring(index, hash.length)
  274. const indexQuery = hash.indexOf('?')
  275. query = query.substring(indexQuery + 1, hash.length)
  276. let vars = query.split("&")
  277. for (let i = 0; i < vars.length; i++) {
  278. let pair = vars[i].split("=")
  279. if (pair[0] == param) {
  280. return pair[1]
  281. }
  282. }
  283. return (false)
  284. }
  285. // 检测微信是否安装
  286. export function checkApp() {
  287. if (plus.runtime.isApplicationExist({
  288. pname: 'com.tencent.mm',
  289. action: 'weixin://'
  290. })) {
  291. return true
  292. console.log("微信应用已安装");
  293. } else {
  294. return false
  295. console.log("微信应用未安装");
  296. }
  297. }
  298. // 数字保留两位小数或保留整数
  299. export function numFixtwo(num) {
  300. let number = Number(num)
  301. // console.log(number,'num');
  302. if (parseInt(number.toString()) == parseFloat(number.toString())) {
  303. return number
  304. } else {
  305. return number.toFixed(2)
  306. }
  307. }