123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705 |
- import test from './test.js'
- import { round } from './digit.js'
- function range(min = 0, max = 0, value = 0) {
- return Math.max(min, Math.min(max, Number(value)))
- }
- function getPx(value, unit = false) {
- if (test.number(value)) {
- return unit ? `${value}px` : Number(value)
- }
-
- if (/(rpx|upx)$/.test(value)) {
- return unit ? `${uni.upx2px(parseInt(value))}px` : Number(uni.upx2px(parseInt(value)))
- }
- return unit ? `${parseInt(value)}px` : parseInt(value)
- }
- function sleep(value = 30) {
- return new Promise((resolve) => {
- setTimeout(() => {
- resolve()
- }, value)
- })
- }
- function os() {
- return uni.getSystemInfoSync().platform.toLowerCase()
- }
- function sys() {
- return uni.getSystemInfoSync()
- }
- function random(min, max) {
- if (min >= 0 && max > 0 && max >= min) {
- const gab = max - min + 1
- return Math.floor(Math.random() * gab + min)
- }
- return 0
- }
- function guid(len = 32, firstU = true, radix = null) {
- const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
- const uuid = []
- radix = radix || chars.length
- if (len) {
-
- for (let i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
- } else {
- let r
-
- uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
- uuid[14] = '4'
- for (let i = 0; i < 36; i++) {
- if (!uuid[i]) {
- r = 0 | Math.random() * 16
- uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]
- }
- }
- }
-
- if (firstU) {
- uuid.shift()
- return `u${uuid.join('')}`
- }
- return uuid.join('')
- }
- function $parent(name = undefined) {
- let parent = this.$parent
-
- while (parent) {
-
- if (parent.$options && parent.$options.name !== name) {
-
- parent = parent.$parent
- } else {
- return parent
- }
- }
- return false
- }
- function addStyle(customStyle, target = 'object') {
-
- if (test.empty(customStyle) || typeof(customStyle) === 'object' && target === 'object' || target === 'string' &&
- typeof(customStyle) === 'string') {
- return customStyle
- }
-
- if (target === 'object') {
-
- customStyle = trim(customStyle)
-
- const styleArray = customStyle.split(';')
- const style = {}
-
- for (let i = 0; i < styleArray.length; i++) {
-
- if (styleArray[i]) {
- const item = styleArray[i].split(':')
- style[trim(item[0])] = trim(item[1])
- }
- }
- return style
- }
-
- let string = ''
- for (const i in customStyle) {
-
- const key = i.replace(/([A-Z])/g, '-$1').toLowerCase()
- string += `${key}:${customStyle[i]};`
- }
-
- return trim(string)
- }
- function addUnit(value = 'auto', unit = uni?.$u?.config?.unit ?? 'px') {
- value = String(value)
-
- return test.number(value) ? `${value}${unit}` : value
- }
- function deepClone(obj) {
-
- if ([null, undefined, NaN, false].includes(obj)) return obj
- if (typeof obj !== 'object' && typeof obj !== 'function') {
-
- return obj
- }
- const o = test.array(obj) ? [] : {}
- for (const i in obj) {
- if (obj.hasOwnProperty(i)) {
- o[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i]
- }
- }
- return o
- }
- function deepMerge(target = {}, source = {}) {
- target = deepClone(target)
- if (typeof target !== 'object' || typeof source !== 'object') return false
- for (const prop in source) {
- if (!source.hasOwnProperty(prop)) continue
- if (prop in target) {
- if (typeof target[prop] !== 'object') {
- target[prop] = source[prop]
- } else if (typeof source[prop] !== 'object') {
- target[prop] = source[prop]
- } else if (target[prop].concat && source[prop].concat) {
- target[prop] = target[prop].concat(source[prop])
- } else {
- target[prop] = deepMerge(target[prop], source[prop])
- }
- } else {
- target[prop] = source[prop]
- }
- }
- return target
- }
- function error(err) {
-
- if (process.env.NODE_ENV === 'development') {
- console.error(`uView提示:${err}`)
- }
- }
- function randomArray(array = []) {
-
- return array.sort(() => Math.random() - 0.5)
- }
- if (!String.prototype.padStart) {
-
- String.prototype.padStart = function(maxLength, fillString = ' ') {
- if (Object.prototype.toString.call(fillString) !== '[object String]') {
- throw new TypeError(
- 'fillString must be String'
- )
- }
- const str = this
-
- if (str.length >= maxLength) return String(str)
- const fillLength = maxLength - str.length
- let times = Math.ceil(fillLength / fillString.length)
- while (times >>= 1) {
- fillString += fillString
- if (times === 1) {
- fillString += fillString
- }
- }
- return fillString.slice(0, fillLength) + str
- }
- }
- function timeFormat(dateTime = null, formatStr = 'yyyy-mm-dd') {
- let date
-
- if (!dateTime) {
- date = new Date()
- }
-
- else if (/^\d{10}$/.test(dateTime?.toString().trim())) {
- date = new Date(dateTime * 1000)
- }
-
- else if (typeof dateTime === 'string' && /^\d+$/.test(dateTime.trim())) {
- date = new Date(Number(dateTime))
- }
-
- else {
-
- date = new Date(
- typeof dateTime === 'string'
- ? dateTime.replace(/-/g, '/')
- : dateTime
- )
- }
- const timeSource = {
- 'y': date.getFullYear().toString(),
- 'm': (date.getMonth() + 1).toString().padStart(2, '0'),
- 'd': date.getDate().toString().padStart(2, '0'),
- 'h': date.getHours().toString().padStart(2, '0'),
- 'M': date.getMinutes().toString().padStart(2, '0'),
- 's': date.getSeconds().toString().padStart(2, '0')
-
- }
- for (const key in timeSource) {
- const [ret] = new RegExp(`${key}+`).exec(formatStr) || []
- if (ret) {
-
- const beginIndex = key === 'y' && ret.length === 2 ? 2 : 0
- formatStr = formatStr.replace(ret, timeSource[key].slice(beginIndex))
- }
- }
- return formatStr
- }
- function timeFrom(timestamp = null, format = 'yyyy-mm-dd') {
- if (timestamp == null) timestamp = Number(new Date())
- timestamp = parseInt(timestamp)
-
- if (timestamp.toString().length == 10) timestamp *= 1000
- let timer = (new Date()).getTime() - timestamp
- timer = parseInt(timer / 1000)
-
- let tips = ''
- switch (true) {
- case timer < 300:
- tips = '刚刚'
- break
- case timer >= 300 && timer < 3600:
- tips = `${parseInt(timer / 60)}分钟前`
- break
- case timer >= 3600 && timer < 86400:
- tips = `${parseInt(timer / 3600)}小时前`
- break
- case timer >= 86400 && timer < 2592000:
- tips = `${parseInt(timer / 86400)}天前`
- break
- default:
- // 如果format为false,则无论什么时间戳,都显示xx之前
- if (format === false) {
- if (timer >= 2592000 && timer < 365 * 86400) {
- tips = `${parseInt(timer / (86400 * 30))}个月前`
- } else {
- tips = `${parseInt(timer / (86400 * 365))}年前`
- }
- } else {
- tips = timeFormat(timestamp, format)
- }
- }
- return tips
- }
- /**
- * @description 去除空格
- * @param String str 需要去除空格的字符串
- * @param String pos both(左右)|left|right|all 默认both
- */
- function trim(str, pos = 'both') {
- str = String(str)
- if (pos == 'both') {
- return str.replace(/^\s+|\s+$/g, '')
- }
- if (pos == 'left') {
- return str.replace(/^\s*/, '')
- }
- if (pos == 'right') {
- return str.replace(/(\s*$)/g, '')
- }
- if (pos == 'all') {
- return str.replace(/\s+/g, '')
- }
- return str
- }
- /**
- * @description 对象转url参数
- * @param {object} data,对象
- * @param {Boolean} isPrefix,是否自动加上"?"
- * @param {string} arrayFormat 规则 indices|brackets|repeat|comma
- */
- function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') {
- const prefix = isPrefix ? '?' : ''
- const _result = []
- if (['indices', 'brackets', 'repeat', 'comma'].indexOf(arrayFormat) == -1) arrayFormat = 'brackets'
- for (const key in data) {
- const value = data[key]
- // 去掉为空的参数
- if (['', undefined, null].indexOf(value) >= 0) {
- continue
- }
- // 如果值为数组,另行处理
- if (value.constructor === Array) {
- // e.g. {ids: [1, 2, 3]}
- switch (arrayFormat) {
- case 'indices':
- // 结果: ids[0]=1&ids[1]=2&ids[2]=3
- for (let i = 0; i < value.length; i++) {
- _result.push(`${key}[${i}]=${value[i]}`)
- }
- break
- case 'brackets':
- // 结果: ids[]=1&ids[]=2&ids[]=3
- value.forEach((_value) => {
- _result.push(`${key}[]=${_value}`)
- })
- break
- case 'repeat':
- // 结果: ids=1&ids=2&ids=3
- value.forEach((_value) => {
- _result.push(`${key}=${_value}`)
- })
- break
- case 'comma':
- // 结果: ids=1,2,3
- let commaStr = ''
- value.forEach((_value) => {
- commaStr += (commaStr ? ',' : '') + _value
- })
- _result.push(`${key}=${commaStr}`)
- break
- default:
- value.forEach((_value) => {
- _result.push(`${key}[]=${_value}`)
- })
- }
- } else {
- _result.push(`${key}=${value}`)
- }
- }
- return _result.length ? prefix + _result.join('&') : ''
- }
- /**
- * 显示消息提示框
- * @param {String} title 提示的内容,长度与 icon 取值有关。
- * @param {Number} duration 提示的延迟时间,单位毫秒,默认:2000
- */
- function toast(title, duration = 2000) {
- uni.showToast({
- title: String(title),
- icon: 'none',
- duration
- })
- }
- /**
- * @description 根据主题type值,获取对应的图标
- * @param {String} type 主题名称,primary|info|error|warning|success
- * @param {boolean} fill 是否使用fill填充实体的图标
- */
- function type2icon(type = 'success', fill = false) {
- // 如果非预置值,默认为success
- if (['primary', 'info', 'error', 'warning', 'success'].indexOf(type) == -1) type = 'success'
- let iconName = ''
- // 目前(2019-12-12),info和primary使用同一个图标
- switch (type) {
- case 'primary':
- iconName = 'info-circle'
- break
- case 'info':
- iconName = 'info-circle'
- break
- case 'error':
- iconName = 'close-circle'
- break
- case 'warning':
- iconName = 'error-circle'
- break
- case 'success':
- iconName = 'checkmark-circle'
- break
- default:
- iconName = 'checkmark-circle'
- }
- // 是否是实体类型,加上-fill,在icon组件库中,实体的类名是后面加-fill的
- if (fill) iconName += '-fill'
- return iconName
- }
- /**
- * @description 数字格式化
- * @param {number|string} number 要格式化的数字
- * @param {number} decimals 保留几位小数
- * @param {string} decimalPoint 小数点符号
- * @param {string} thousandsSeparator 千分位符号
- * @returns {string} 格式化后的数字
- */
- function priceFormat(number, decimals = 0, decimalPoint = '.', thousandsSeparator = ',') {
- number = (`${number}`).replace(/[^0-9+-Ee.]/g, '')
- const n = !isFinite(+number) ? 0 : +number
- const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
- const sep = (typeof thousandsSeparator === 'undefined') ? ',' : thousandsSeparator
- const dec = (typeof decimalPoint === 'undefined') ? '.' : decimalPoint
- let s = ''
- s = (prec ? round(n, prec) + '' : `${Math.round(n)}`).split('.')
- const re = /(-?\d+)(\d{3})/
- while (re.test(s[0])) {
- s[0] = s[0].replace(re, `$1${sep}$2`)
- }
-
- if ((s[1] || '').length < prec) {
- s[1] = s[1] || ''
- s[1] += new Array(prec - s[1].length + 1).join('0')
- }
- return s.join(dec)
- }
- /**
- * @description 获取duration值
- * 如果带有ms或者s直接返回,如果大于一定值,认为是ms单位,小于一定值,认为是s单位
- * 比如以30位阈值,那么300大于30,可以理解为用户想要的是300ms,而不是想花300s去执行一个动画
- * @param {String|number} value 比如: "1s"|"100ms"|1|100
- * @param {boolean} unit 提示: 如果是false 默认返回number
- * @return {string|number}
- */
- function getDuration(value, unit = true) {
- const valueNum = parseInt(value)
- if (unit) {
- if (/s$/.test(value)) return value
- return value > 30 ? `${value}ms` : `${value}s`
- }
- if (/ms$/.test(value)) return valueNum
- if (/s$/.test(value)) return valueNum > 30 ? valueNum : valueNum * 1000
- return valueNum
- }
- /**
- * @description 日期的月或日补零操作
- * @param {String} value 需要补零的值
- */
- function padZero(value) {
- return `00${value}`.slice(-2)
- }
- /**
- * @description 在u-form的子组件内容发生变化,或者失去焦点时,尝试通知u-form执行校验方法
- * @param {*} instance
- * @param {*} event
- */
- function formValidate(instance, event) {
- const formItem = uni.$u.$parent.call(instance, 'u-form-item')
- const form = uni.$u.$parent.call(instance, 'u-form')
- // 如果发生变化的input或者textarea等,其父组件中有u-form-item或者u-form等,就执行form的validate方法
- // 同时将form-item的pros传递给form,让其进行精确对象验证
- if (formItem && form) {
- form.validateField(formItem.prop, () => {}, event)
- }
- }
- /**
- * @description 获取某个对象下的属性,用于通过类似'a.b.c'的形式去获取一个对象的的属性的形式
- * @param {object} obj 对象
- * @param {string} key 需要获取的属性字段
- * @returns {*}
- */
- function getProperty(obj, key) {
- if (!obj) {
- return
- }
- if (typeof key !== 'string' || key === '') {
- return ''
- }
- if (key.indexOf('.') !== -1) {
- const keys = key.split('.')
- let firstObj = obj[keys[0]] || {}
- for (let i = 1; i < keys.length; i++) {
- if (firstObj) {
- firstObj = firstObj[keys[i]]
- }
- }
- return firstObj
- }
- return obj[key]
- }
- /**
- * @description 设置对象的属性值,如果'a.b.c'的形式进行设置
- * @param {object} obj 对象
- * @param {string} key 需要设置的属性
- * @param {string} value 设置的值
- */
- function setProperty(obj, key, value) {
- if (!obj) {
- return
- }
- // 递归赋值
- const inFn = function(_obj, keys, v) {
- // 最后一个属性key
- if (keys.length === 1) {
- _obj[keys[0]] = v
- return
- }
- // 0~length-1个key
- while (keys.length > 1) {
- const k = keys[0]
- if (!_obj[k] || (typeof _obj[k] !== 'object')) {
- _obj[k] = {}
- }
- const key = keys.shift()
- // 自调用判断是否存在属性,不存在则自动创建对象
- inFn(_obj[k], keys, v)
- }
- }
- if (typeof key !== 'string' || key === '') {
- } else if (key.indexOf('.') !== -1) { // 支持多层级赋值操作
- const keys = key.split('.')
- inFn(obj, keys, value)
- } else {
- obj[key] = value
- }
- }
- /**
- * @description 获取当前页面路径
- */
- function page() {
- const pages = getCurrentPages()
- // 某些特殊情况下(比如页面进行redirectTo时的一些时机),pages可能为空数组
- return `/${pages[pages.length - 1]?.route ?? ''}`
- }
- /**
- * @description 获取当前路由栈实例数组
- */
- function pages() {
- const pages = getCurrentPages()
- return pages
- }
- /**
- * @description 修改uView内置属性值
- * @param {object} props 修改内置props属性
- * @param {object} config 修改内置config属性
- * @param {object} color 修改内置color属性
- * @param {object} zIndex 修改内置zIndex属性
- */
- function setConfig({
- props = {},
- config = {},
- color = {},
- zIndex = {}
- }) {
- const {
- deepMerge,
- } = uni.$u
- uni.$u.config = deepMerge(uni.$u.config, config)
- uni.$u.props = deepMerge(uni.$u.props, props)
- uni.$u.color = deepMerge(uni.$u.color, color)
- uni.$u.zIndex = deepMerge(uni.$u.zIndex, zIndex)
- }
- export default {
- range,
- getPx,
- sleep,
- os,
- sys,
- random,
- guid,
- $parent,
- addStyle,
- addUnit,
- deepClone,
- deepMerge,
- error,
- randomArray,
- timeFormat,
- timeFrom,
- trim,
- queryParams,
- toast,
- type2icon,
- priceFormat,
- getDuration,
- padZero,
- formValidate,
- getProperty,
- setProperty,
- page,
- pages,
- setConfig
- }
|