utils.js 7.4 KB

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