util.js
9.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import Vue from 'vue'
import { Toast, Dialog } from 'vant'
/**
* 日期格式化
* let time = new Date().format('yyyy-MM-dd hh:mm:ss')
*/
Date.prototype.format = function (fmt) {
let o = {
'M+': this.getMonth() + 1, //月份
'd+': this.getDate(), //日
'h+': this.getHours(), //小时
'm+': this.getMinutes(), //分
's+': this.getSeconds(), //秒
//季度
'q+': Math.floor((this.getMonth() + 3) / 3),
S: this.getMilliseconds() //毫秒
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
}
}
return fmt
}
const iosTimeFormat = time => {
return time.replace(/-/g, '/')
}
const throttle = (fn, gapTime) => {
if (gapTime == null || gapTime == undefined) {
gapTime = 1500
}
let _lastTime = null
return function () {
let _nowTime = +new Date()
if (_nowTime - _lastTime > gapTime || !_lastTime) {
fn.apply(this, arguments)
_lastTime = _nowTime
}
}
}
const debounce = (fn, delay = 500) => {
// timer 是在闭包中的
let timer = null
return function () {
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, arguments)
}, delay)
}
}
/**防止重复点击 */
const showLoading = (title = '加载中...') => {
Toast({
type: 'loading',
message: title,
forbidClick: true,
duration: 0
})
}
const hideLoading = () => {
Toast.clear()
}
/**num:要转换的数值,fixed:精确几位小数 */
const decimal = (num, fixed = 2) => {
let pow = Math.pow(10, fixed)
return Math.round(num * pow) / pow
}
const showToast = (message = '', callBack) => {
hideLoading()
let params = {
message,
forbidClick: true,
duration: 1500
}
Toast(params)
if (callBack && typeof callBack == 'function') {
setTimeout(() => {
callBack()
}, 1500)
}
}
/**触摸样式 */
const touchstart = e => {
e.target.classList.add('btn-on-leave')
}
const touchend = e => {
e.target.classList.remove('btn-on-leave')
}
const setSessionId = val => {
window.localStorage.setItem('wx_scrm_session_id', val)
}
const getSessionId = () => {
return window.localStorage.getItem('wx_scrm_session_id')
}
const clearSessionId = () => {
window.localStorage.removeItem('wx_scrm_session_id')
window.localStorage.removeItem('dj_scrm_session_id')
}
const setAppId = val => {
window.localStorage.setItem('wx_scrm_app_id', val)
}
const getAppId = () => {
return window.localStorage.getItem('wx_scrm_app_id')
}
const setUserInfo = val => {
setLocalStorage('wx_scrm_user_info', val)
}
const getUserInfo = () => {
return getLocalStorage('wx_scrm_user_info')
}
const setLocalStorage = (key, item) => {
window.localStorage.setItem(key, JSON.stringify(item))
}
const getLocalStorage = key => {
let store = JSON.parse(window.localStorage.getItem(key))
if (key == 'wx_scrm_link_params') {
if (!store || Object.keys(store).length < 0) {
store = getPageQuery()
}
}
return store
}
const getPageQuery = name => {
let [url, paramsList] = window.location.href.split('?')
if (!paramsList) return name ? null : {}
let param = paramsList.split('&')
let obj = {}
param.map(e => {
let [key, value] = e.split('=')
obj[key] = value
})
return name ? obj[name] : obj
}
const removeLocalStorage = key => {
window.localStorage.removeItem(key)
}
const dialog = (params = {}) => {
if (!params.confirmButtonColor) params.confirmButtonColor = '#FF7336'
return Dialog.confirm(params)
}
/**拨打电话 */
const makePhoneCall = phoneNumber => {
window.location.href = `tel://${phoneNumber}`
}
/**是否全面屏 */
const isFullSucreen = () => {
let result = false
const rate = window.screen.height / window.screen.width
let limit = window.screen.height == window.screen.availHeight ? 1.8 : 1.65 // 临界判断值
result = rate > limit
return result
}
const jumpChildrenPage = (to, params) => {
let { name } = window.vm._route
window.vm.$router.push({ name: `${name}.${to}`, params })
}
/**拷贝 */
const setClipboardData = data => {
wx.setClipboardData({
data,
success (res) {
Toast('复制成功')
}
})
}
/**接口请求时失败让用户刷新 */
const refreshPage = (message = '系统异常', confirmButtonText) => {
return Dialog.alert({
message,
theme: 'round-button',
confirmButtonText: confirmButtonText || '点击重试',
confirmButtonColor: '#f13c3d'
})
}
const toTop = (top = 0) => {
window.scrollTo({
top,
left: 0,
behavior: 'smooth'
})
}
const getParams = name => {
return name ? window.vm.$route.params[name] : window.vm.$route.params
}
const getQuery = () => {
return window.vm.$route.query
}
const watchPageBack = () => {
return new Promise(resolve => {
if (window.$back) {
window.$back = false
resolve()
}
})
}
/**分转元 */
const centsToyuan = price => {
return decimal(Number(price) / 100, 2).toFixed(2)
}
/**设置cookie */
const setCookie = (c_name, value, expiredays = 365) => {
let exdate = new Date()
console.log(c_name, value)
exdate.setDate(exdate.getDate() + expiredays)
document.cookie = c_name + '=' + value + (expiredays == null ? '' : ';expires=' + exdate.toGMTString())
}
/**获取cookie */
const getCookie = c_name => {
if (document.cookie.length > 0) {
let c_start = document.cookie.indexOf(c_name + '=')
if (c_start != -1) {
c_start = c_start + c_name.length + 1
let c_end = document.cookie.indexOf(';', c_start)
if (c_end == -1) c_end = document.cookie.length
return unescape(document.cookie.substring(c_start, c_end))
}
}
return ''
}
/*转中文 */
const toUnicode = (chineseStr = '') => {
let unicodeStr = ''
for (let i = 0, iLength = chineseStr.length; i < iLength; i++) {
unicodeStr += '@' + chineseStr.charCodeAt(i).toString(16)
}
return unicodeStr
}
const isMobileDevice = () => {
//判断当前设备是否为移动端
const ua = navigator.userAgent.toLowerCase()
const t1 = /android|webos|iphone|ipad|ipod|blackberry|iemobile|OpenHarmony|Harmony|opera mini/i.test(ua)
const t2 = !ua.match('iphone') && navigator.maxTouchPoints > 1
return t1 || t2
}
/**秒数转天时分秒*/
const date_format = num => {
const addZero = i => (i < 10 ? `0${i}` : `${i}`)
//计算剩余的天数
let days = addZero(parseInt(num / 60 / 60 / 24, 10))
//计算剩余的小时
let hours = addZero(parseInt((num / 60 / 60) % 24, 10))
//计算剩余的分钟
let minutes = addZero(parseInt((num / 60) % 60, 10))
//计算剩余的秒数
let second = addZero(parseInt(num % 60, 10))
if (days == 0) {
return `${hours}:${minutes}:${second}`
}
return `${days}天${hours}:${minutes}:${second}`
}
const draggable = (drag, fun, target) => {
var startEvt, moveEvt, endEvt
// 判断是否支持触摸事件
if ('ontouchstart' in window) {
startEvt = 'touchstart'
moveEvt = 'touchmove'
endEvt = 'touchend'
} else {
startEvt = 'mousedown'
moveEvt = 'mousemove'
endEvt = 'mouseup'
}
drag.style.cursor = 'grab'
var disX, disY, left, top, starX, starY, oLeft, oTop
drag.addEventListener(startEvt, startFun)
function startFun (event) {
// console.log('event', )
let className = event.target.className
if (!drag.id || className.includes(target)) return
// 阻止页面的滚动,缩放
event.preventDefault()
// 兼容IE浏览器
drag.style.cursor = 'grabbing'
var e = event || window.event
oLeft = drag.offsetLeft
oTop = drag.offsetTop
// 手指按下时的坐标
starX = e.touches ? e.touches[0].clientX : e.clientX
starY = e.touches ? e.touches[0].clientY : e.clientY
// 手指相对于拖动元素左上角的位置
disX = starX - drag.offsetLeft
disY = starY - drag.offsetTop
// 按下之后才监听后续事件
document.addEventListener(moveEvt, moveFun)
document.addEventListener(endEvt, endFun)
}
function moveFun (event) {
// 兼容IE浏览器
var e = event || window.event
left = (e.touches ? e.touches[0].clientX : e.clientX) - disX
top = (e.touches ? e.touches[0].clientY : e.clientY) - disY
// 限制拖拽的X范围,不能拖出屏幕
if (left < 0) {
left = 0
} else if (left > document.documentElement.clientWidth - drag.offsetWidth) {
left = document.documentElement.clientWidth - drag.offsetWidth
}
// 限制拖拽的Y范围,不能拖出屏幕
if (top < 0) {
top = 0
} else if (top > window.innerHeight - drag.offsetHeight) {
top = window.innerHeight - drag.offsetHeight
}
drag.style.left = left + 'px'
drag.style.top = top + 'px'
}
function endFun (event) {
drag.style.cursor = ''
document.removeEventListener(moveEvt, moveFun)
document.removeEventListener(endEvt, endFun)
if (oLeft == drag.offsetLeft && oTop == drag.offsetTop && fun) {
// 点击
fun()
}
}
}
const clearObjNull = options => {
let obj = {}
Object.keys(options).map(e => {
if (options[e] != null && options[e] != undefined) {
if (typeof options[e] == 'object') {
Object.keys(options[e]).map(key => {
if (options[e][key] == null || options[e][key] == undefined) delete options[e][key]
})
}
obj[e] = options[e]
}
})
return obj
}
const utils = {
removeLocalStorage,
setClipboardData,
jumpChildrenPage,
setLocalStorage,
getLocalStorage,
clearSessionId,
isMobileDevice,
makePhoneCall,
isFullSucreen,
watchPageBack,
iosTimeFormat,
setSessionId,
getPageQuery,
getSessionId,
clearObjNull,
showLoading,
centsToyuan,
setUserInfo,
getUserInfo,
hideLoading,
refreshPage,
date_format,
touchstart,
showToast,
getParams,
toUnicode,
setCookie,
getCookie,
draggable,
setAppId,
getAppId,
debounce,
getQuery,
touchend,
throttle,
decimal,
dialog,
toTop
}
Object.keys(utils).map(key => {
Vue.prototype[key] = utils[key]
})
export default utils