Files

167 lines
3.1 KiB
JavaScript
Raw Permalink Normal View History

2026-08-17 11:01:21 +08:00
export * from './storage'
export * from './auth'
export * from './platform'
export {
default as request, get, post, put, del, upload
}
from './request'
/**
* 防抖函数
* @param {Function} fn 目标函数
* @param {number} [delay=300] 延迟毫秒
* @returns {Function}
*/
export function debounce(fn, delay = 300) {
let timer = null
return function(...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
timer = null
}, delay)
}
}
/**
* 节流函数
* @param {Function} fn 目标函数
* @param {number} [interval=300] 间隔毫秒
* @returns {Function}
*/
export function throttle(fn, interval = 300) {
let lastTime = 0
return function(...args) {
const now = Date.now()
if (now - lastTime >= interval) {
lastTime = now
fn.apply(this, args)
}
}
}
/**
* 深拷贝
* @param {*} obj
* @returns {*}
*/
export function deepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj
if (obj instanceof Date) return new Date(obj)
if (obj instanceof RegExp) return new RegExp(obj)
const clone = Array.isArray(obj) ? [] : {}
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
clone[key] = deepClone(obj[key])
}
}
return clone
}
/**
* 延迟执行(Promise 版 setTimeout
* @param {number} ms 毫秒
* @returns {Promise}
*/
export function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
/**
* 生成唯一 ID
* @returns {string}
*/
export function generateId() {
return Date.now().toString(36) + Math.random().toString(36).substring(2)
}
/**
* 页面跳转封装
*/
export const router = {
push(url, params) {
const query = params ? '?' + objectToQuery(params) : ''
uni.navigateTo({
url: url + query
})
},
replace(url, params) {
const query = params ? '?' + objectToQuery(params) : ''
uni.redirectTo({
url: url + query
})
},
reLaunch(url, params) {
const query = params ? '?' + objectToQuery(params) : ''
uni.reLaunch({
url: url + query
})
},
switchTab(url) {
uni.switchTab({
url
})
},
back(delta = 1) {
uni.navigateBack({
delta
})
},
}
/**
* 对象转查询字符串
* @param {Object} obj
* @returns {string}
*/
export function objectToQuery(obj) {
return Object.keys(obj)
.filter((key) => obj[key] !== undefined && obj[key] !== null)
.map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
.join('&')
}
/**
* 显示消息提示
*/
export const toast = {
success(title, duration = 1500) {
uni.showToast({
title,
icon: 'success',
duration
})
},
error(title, duration = 2000) {
uni.showToast({
title,
icon: 'none',
duration
})
},
loading(title = '加载中...') {
uni.showLoading({
title,
mask: true
})
},
hideLoading() {
uni.hideLoading()
},
}
/**
* 确认弹窗(Promise 版)
* @param {string} content 内容
* @param {string} [title='提示'] 标题
* @returns {Promise<boolean>}
*/
export function confirm(content, title = '提示') {
return new Promise((resolve) => {
uni.showModal({
title,
content,
success: (res) => resolve(!!res.confirm),
})
})
}