Appearance
- default
- chenghua
- shijingshan
- sybz
- gulou
无数据
Appearance
本页收录 @sybz-components/utils 当前对外导出的全部工具方法,并为每个方法补一个最小示例,方便直接查用法。
以下示例默认已经从 @sybz-components/utils 引入对应方法;依赖 window、document、localStorage 或 Element Plus 的方法,需要在浏览器环境中使用。
在应用入口调用一次 configureUtils,即可为支持主题的工具函数设置默认主题。theme 可选值为 'default' | 'chenghua' | 'shijingshan',默认值为 'default';单次调用传入的 theme 优先级更高。
import { configureUtils } from '@sybz-components/utils'
configureUtils({
theme: 'shijingshan',
http: {
baseURL: '/api',
getToken: () => localStorage.getItem('token'),
},
})import { configureUtils } from '@sybz-components/utils'
configureUtils({
theme: 'shijingshan',
http: {
baseURL: '/api',
getToken: () => localStorage.getItem('token'),
},
})配置后,confirm 和 $toast 无需重复传入主题:
await confirm({ variant: 'delete', target: '示例数据' })
$toast('删除成功')
// 单次覆盖全局主题
$toast({ message: '使用成华主题', theme: 'chenghua' })
await confirm('使用默认主题', { theme: 'default' })await confirm({ variant: 'delete', target: '示例数据' })
$toast('删除成功')
// 单次覆盖全局主题
$toast({ message: '使用成华主题', theme: 'chenghua' })
await confirm('使用默认主题', { theme: 'default' })http 也在这里配置一次,之后直接从 @sybz-components/utils 引入全局客户端:
import { http } from '@sybz-components/utils'
const users = await http.get('/users')import { http } from '@sybz-components/utils'
const users = await http.get('/users')export * from './base'
export * from './confirmSemantic'
export * from './is'
export * from './format'
export * from './theme'
export * from './http'export * from './base'
export * from './confirmSemantic'
export * from './is'
export * from './format'
export * from './theme'
export * from './http'用于快速显示消息提示。
$toast('保存成功')
$toast('保存失败', 'e')
$toast.success('创建完成')$toast('保存成功')
$toast('保存失败', 'e')
$toast.success('创建完成')清理 localStorage / sessionStorage 中的指定项,或按排除项整体清空。
clearStorage('token')
clearStorage(['token', 'userInfo'])
clearStorage({ exclude: ['theme', 'language'] })clearStorage('token')
clearStorage(['token', 'userInfo'])
clearStorage({ exclude: ['theme', 'language'] })深拷贝对象;如果传入数组,还可以按次数复制数组内容。
const obj = clone({ name: 'andy', extra: { id: 1 } })
const list = clone([1, 2, 3], 2)const obj = clone({ name: 'andy', extra: { id: 1 } })
const list = clone([1, 2, 3], 2)基于 ElMessageBox.confirm 的确认框封装。
await confirm('确定删除当前记录吗?', {
confirmButtonText: '删除',
})await confirm('确定删除当前记录吗?', {
confirmButtonText: '删除',
})复制文本到剪贴板,并默认弹出成功提示。
copy('sybz-components')
copy('静默复制', { hideToast: true })copy('sybz-components')
copy('静默复制', { hideToast: true })防抖函数,常用于搜索输入、窗口尺寸变化等场景。
const search = debounce((keyword: string) => {
console.log('search:', keyword)
}, 300)
search('sybz')
const submit = debounce(
async () => {
return await saveForm()
},
500,
true,
(result) => {
console.log('保存结果:', result)
},
)
submit.cancel()const search = debounce((keyword: string) => {
console.log('search:', keyword)
}, 300)
search('sybz')
const submit = debounce(
async () => {
return await saveForm()
},
500,
true,
(result) => {
console.log('保存结果:', result)
},
)
submit.cancel()把字节数格式化成更易读的单位字符串。
formatBytes(1024) // 1.00 KB
formatBytes(1048576, { digit: 1, suffix: '/s' }) // 1.0 MB/sformatBytes(1024) // 1.00 KB
formatBytes(1048576, { digit: 1, suffix: '/s' }) // 1.0 MB/s把 KB / MB / GB 这类字符串还原成字节数。
formatBytesConvert('1.5GB')
formatBytesConvert('1,024 KB')formatBytesConvert('1.5GB')
formatBytesConvert('1,024 KB')把持续时间时间戳格式化成“天 / 时 / 分 / 秒”文本。
formatDurationTime(1162821) // 19分22秒
formatDurationTime(5 * 60 * 1000, '{i}分{s}秒')formatDurationTime(1162821) // 19分22秒
formatDurationTime(5 * 60 * 1000, '{i}分{s}秒')将换行和缩进转换为适合直接展示的 HTML 字符串。
formatTextToHtml('第1行\n第2行\n\t缩进内容')formatTextToHtml('第1行\n第2行\n\t缩进内容')为数字增加千分位分隔符。
formatThousands(1234567)
formatThousands('1234567.89MB')formatThousands(1234567)
formatThousands('1234567.89MB')把时间格式化成指定模板字符串。
formatTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
formatTime(1713926400, '{y}/{m}/{d}')formatTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
formatTime(1713926400, '{y}/{m}/{d}')按指定小数位补全数字,也支持前后缀和保留单位。
formatToFixed('22.1', 2) // 22.10
formatToFixed('22 TB', { digit: 2, unit: false, prefix: '$' }) // $22.00formatToFixed('22.1', 2) // 22.10
formatToFixed('22 TB', { digit: 2, unit: false, prefix: '$' }) // $22.00从 localStorage 或 sessionStorage 中读取数据,并自动尝试反序列化。
const token = getStorage('token')
const userInfo = getStorage<{ id: number; name: string }>('userInfo')
const draft = getStorage('formDraft', true)const token = getStorage('token')
const userInfo = getStorage<{ id: number; name: string }>('userInfo')
const draft = getStorage('formDraft', true)返回更直观的小写类型字符串。
getType([]) // array
getType(new Date()) // date
getType(null) // nullgetType([]) // array
getType(new Date()) // date
getType(null) // null读取根节点上的 CSS 变量值。
const brandColor = getVariable('--vp-c-brand-1')const brandColor = getVariable('--vp-c-brand-1')判断值是否为数组。
isArray([1, 2, 3]) // true
isArray({ length: 3 }) // falseisArray([1, 2, 3]) // true
isArray({ length: 3 }) // false判断值是否为布尔值。
isBoolean(false) // true
isBoolean(0) // falseisBoolean(false) // true
isBoolean(0) // false判断对象是否为 Vue 组件配置。
isComponent({
render() {
return null
},
})isComponent({
render() {
return null
},
})判断值是否为 Date 对象。
isDate(new Date()) // true
isDate('2026-04-24') // falseisDate(new Date()) // true
isDate('2026-04-24') // false判断值是否为空。当前默认不会把 0 和 false 当成空值。
isEmpty(' ') // true
isEmpty(0) // false
isEmpty(0, false) // true,兼容旧语义isEmpty(' ') // true
isEmpty(0) // false
isEmpty(0, false) // true,兼容旧语义判断值是否为空对象。
isEmptyObject({}) // true
isEmptyObject({ id: 1 }) // falseisEmptyObject({}) // true
isEmptyObject({ id: 1 }) // false判断值是否为函数。
isFunction(() => {}) // true
isFunction('fn') // falseisFunction(() => {}) // true
isFunction('fn') // false根据 userAgent 判断当前环境是否为 iOS。
if (isIOS()) {
console.log('当前是 iOS 设备')
}if (isIOS()) {
console.log('当前是 iOS 设备')
}判断值是否为 Map。
isMap(new Map()) // true
isMap({}) // falseisMap(new Map()) // true
isMap({}) // false判断值是否为数字类型。
isNumber(12) // true
isNumber('12') // falseisNumber(12) // true
isNumber('12') // false判断值是否为对象且不为 null。
isObject({ id: 1 }) // true
isObject(null) // falseisObject({ id: 1 }) // true
isObject(null) // false判断值是否为普通对象。
isPlainObject({ id: 1 }) // true
isPlainObject(new Date()) // falseisPlainObject({ id: 1 }) // true
isPlainObject(new Date()) // false判断值是否为 Promise 风格对象。
isPromise(Promise.resolve(1)) // true
isPromise({ then: () => {} }) // falseisPromise(Promise.resolve(1)) // true
isPromise({ then: () => {} }) // false判断值是否为正则对象。
isRegExp(/sybz/i) // true
isRegExp('sybz') // falseisRegExp(/sybz/i) // true
isRegExp('sybz') // false判断值是否为 Set。
isSet(new Set([1, 2, 3])) // true
isSet([1, 2, 3]) // falseisSet(new Set([1, 2, 3])) // true
isSet([1, 2, 3]) // false判断值是否为字符串。
isString('sybz') // true
isString(123) // falseisString('sybz') // true
isString(123) // false判断字符串是否可以被转成有效数字。
isStringNumber('12.5') // true
isStringNumber('12px') // falseisStringNumber('12.5') // true
isStringNumber('12px') // false判断节点是否为 SVGElement。
const svg = document.querySelector('svg')
isSVGElement(svg)const svg = document.querySelector('svg')
isSVGElement(svg)判断值是否为 Symbol。
isSymbol(Symbol('id')) // true
isSymbol('id') // falseisSymbol(Symbol('id')) // true
isSymbol('id') // false判断字符串是否为合法链接。
isUrl('https://sybz-components.com') // true
isUrl('/local/path') // falseisUrl('https://sybz-components.com') // true
isUrl('/local/path') // false对 console.log 的简单封装,输出时会额外带上变量名。
const formData = { id: 1, name: 'andy' }
log('formData', formData)const formData = { id: 1, name: 'andy' }
log('formData', formData)合并两个对象;同名字段都存在时,以第二个对象为准。
merge({ name: '', age: 18, city: 'beijing' }, { name: 'andy', age: 20, city: '' })merge({ name: '', age: 18, city: 'beijing' }, { name: 'andy', age: 20, city: '' })Object.prototype.toString 的直接别名。
objectToString.call([]) // [object Array]
objectToString.call(new Date()) // [object Date]objectToString.call([]) // [object Array]
objectToString.call(new Date()) // [object Date]测试导出方法。
onlyTest() // testonlyTest() // test把宽度值转换成统一的 CSS 写法。
processWidth(200) // { width: '200px' }
processWidth('50%', true) // 50%processWidth(200) // { width: '200px' }
processWidth('50%', true) // 50%生成指定范围内的随机整数。
random() // 0 ~ 10
random(100, 999) // 100 ~ 999random() // 0 ~ 10
random(100, 999) // 100 ~ 999向 localStorage 或 sessionStorage 写入数据。
setStorage('token', 'abc123')
setStorage('userInfo', { id: 1, name: 'andy' })
setStorage('formDraft', { keyword: '机房', page: 2 }, true)setStorage('token', 'abc123')
setStorage('userInfo', { id: 1, name: 'andy' })
setStorage('formDraft', { keyword: '机房', page: 2 }, true)创建一个可 await 的延迟。
await delay(500)
await delay(1000, () => console.log('1 秒后执行'))await delay(500)
await delay(1000, () => console.log('1 秒后执行'))返回当前 utils 构建时间。
getUtilsBuildTime()getUtilsBuildTime()节流函数,适合滚动、拖拽、窗口变化等高频事件。
const handleResize = throttle(() => {
console.log('resize')
}, 300)
window.addEventListener('resize', handleResize)
const saveDraft = throttle(
(content: string) => {
return content.trim()
},
1000,
{ leading: false, trailing: true },
(result) => {
console.log('保存草稿:', result)
},
)
saveDraft('hello')
saveDraft.flush()
saveDraft.cancel()const handleResize = throttle(() => {
console.log('resize')
}, 300)
window.addEventListener('resize', handleResize)
const saveDraft = throttle(
(content: string) => {
return content.trim()
},
1000,
{ leading: false, trailing: true },
(result) => {
console.log('保存草稿:', result)
},
)
saveDraft('hello')
saveDraft.flush()
saveDraft.cancel()把驼峰字符串转换成连接符形式。
toLine('inputNumber') // input-number
toLine('CompTitle', '_') // comp_titletoLine('inputNumber') // input-number
toLine('CompTitle', '_') // comp_title返回更短的原始类型名称。
toRawType(new Map()) // Map
toRawType([]) // ArraytoRawType(new Map()) // Map
toRawType([]) // Array返回完整的 Object.prototype.toString 结果。
toTypeString([]) // [object Array]
toTypeString(Promise.resolve()) // [object Promise]toTypeString([]) // [object Array]
toTypeString(Promise.resolve()) // [object Promise]统一处理 Promise 或任务函数执行结果,返回固定的 { data, error }。
const loadList = async () => ({ list: [] })
const { data, error } = await tryCatch(() => loadList())
if (!error) {
console.log(data?.list)
}const loadList = async () => ({ list: [] })
const { data, error } = await tryCatch(() => loadList())
if (!error) {
console.log(data?.list)
}生成随机字符串,也支持手机号、邮箱、时间串、数字等特殊模式。
mockValue() // 普通随机串
mockValue('phone') // 随机手机号
mockValue('number', 6) // 6 位数字mockValue() // 普通随机串
mockValue('phone') // 随机手机号
mockValue('number', 6) // 6 位数字生成 Element Plus 表单规则,或在 pureValid=true 时直接返回布尔结果。
const mobileRule = validate('mobile')
const selectRule = validate('change') // 默认提示:请选择
const emailRule = validate({ type: 'email', message: '请输入邮箱' })
const isIp = validate('ip', '192.168.1.10', true)const mobileRule = validate('mobile')
const selectRule = validate('change') // 默认提示:请选择
const emailRule = validate({ type: 'email', message: '请输入邮箱' })
const isIp = validate('ip', '192.168.1.10', true)在 validate 基础上补齐默认空触发时机,只在提交或手动调用表单校验时触发。validate 默认触发时机是 ['blur', 'change']。
const nameRule = validateOnSubmit('required', {
message: '请输入名称',
})const nameRule = validateOnSubmit('required', {
message: '请输入名称',
})对 el-form 的 validate 做 Promise 封装,便于直接 await。
await validateForm(formRef)
await validateForm(formRef, {
message: '请先完善表单信息',
detail: true,
})await validateForm(formRef)
await validateForm(formRef, {
message: '请先完善表单信息',
detail: true,
})