提交 9b9dcb4f authored 作者: 黎九's avatar 黎九

bug修复

上级 a8bfe986
{ {
"name" : "荣县随手拍", "name" : "荣县随手拍",
"appid" : "__UNI__BD3107B", "appid" : "__UNI__7F4BF0D",
"description" : "", "description" : "",
"versionName" : "1.0.0", "versionName" : "1.0.0",
"versionCode" : "100", "versionCode" : "100",
......
...@@ -68,6 +68,7 @@ export default { ...@@ -68,6 +68,7 @@ export default {
onLoad(query) { onLoad(query) {
this.query = query; this.query = query;
console.log(query);
this.fetchPhotoTaskTypeData(); this.fetchPhotoTaskTypeData();
this.fetchPhotoTaskTypeDetail(); this.fetchPhotoTaskTypeDetail();
...@@ -80,7 +81,7 @@ export default { ...@@ -80,7 +81,7 @@ export default {
async fetchPhotoTaskTypeData() { async fetchPhotoTaskTypeData() {
const { list } = await uni.$u.http.get('/api/app/phototasktype/list', { params: { parent_id: this.query.id } }); const { list } = await uni.$u.http.get('/api/app/phototasktype/list', { params: { parent_id: this.query.id } });
this.list = list; this.list = list;
console.log(list);
// 可分类 // 可分类
if (list.some(v => v.category > 0)) { if (list.some(v => v.category > 0)) {
this.totalList = Object.keys(categoryMap).map((c, index) => { this.totalList = Object.keys(categoryMap).map((c, index) => {
...@@ -124,11 +125,14 @@ export default { ...@@ -124,11 +125,14 @@ export default {
}, },
onListClick(item, index) { onListClick(item, index) {
if (!this.isFirstRecordType) { if (!this.isFirstRecordType) {
console.log(123,'Tt');
this.isFirstRecordTypeId = item.id; this.isFirstRecordTypeId = item.id;
this.showReport = true; this.showReport = true;
return; return;
} }
console.log('ccc');
uni.$u.route({ uni.$u.route({
url: 'pages/record-content/index', url: 'pages/record-content/index',
params: { params: {
...@@ -139,8 +143,11 @@ export default { ...@@ -139,8 +143,11 @@ export default {
}, },
getIsFirstRecordType() { getIsFirstRecordType() {
const isFirstRecordType = uni.getStorageSync('isFirstRecordType'); let isFirstRecordType = uni.getStorageSync('isFirstRecordType');
if (!isFirstRecordType) uni.setStorageSync('isFirstRecordType', 1); if (!isFirstRecordType){
uni.setStorageSync('isFirstRecordType', 1);
isFirstRecordType = uni.getStorageSync('isFirstRecordType');
}
return isFirstRecordType; return isFirstRecordType;
}, },
}, },
......
...@@ -84,6 +84,7 @@ export default { ...@@ -84,6 +84,7 @@ export default {
// this.fetchPhotoTaskTypeDetail(); // this.fetchPhotoTaskTypeDetail();
this.isFirstRecord = this.getIsFirstRecord(); this.isFirstRecord = this.getIsFirstRecord();
// console.log(this.isFirstRecord);
}, },
onShow(options) {}, onShow(options) {},
...@@ -99,7 +100,7 @@ export default { ...@@ -99,7 +100,7 @@ export default {
async fetchPhotoTaskTypeDetail() { async fetchPhotoTaskTypeDetail() {
const { detail } = await uni.$u.http.get('/api/app/phototasktype/detail', { params: { id: 0 } }); const { detail } = await uni.$u.http.get('/api/app/phototasktype/detail', { params: { id: 0 } });
console.log(detail); // console.log(detail);
}, },
async fetchFalutTask(id) { async fetchFalutTask(id) {
...@@ -140,17 +141,28 @@ export default { ...@@ -140,17 +141,28 @@ export default {
}, },
onListClick(item, index) { onListClick(item, index) {
// console.log(this.isFirstRecord);
if (!this.isFirstRecord) { if (!this.isFirstRecord) {
// console.log(123);
this.isFirstRecordId = item.id; this.isFirstRecordId = item.id;
this.showReport = true; this.showReport = true;
return; return;
} }
uni.$u.route({ url: 'pages/record-type/index', params: { id: item.id } }); // console.log(123,'ttc');
uni.$u.route({ url: 'pages/record-type/index',
params: {
id: item.id,
} ,
});
}, },
getIsFirstRecord() { getIsFirstRecord() {
const isFirstRecord = uni.getStorageSync('isFirstRecord'); let isFirstRecord = uni.getStorageSync('isFirstRecord');
if (!isFirstRecord) uni.setStorageSync('isFirstRecord', 1); if (!isFirstRecord){
uni.setStorageSync('isFirstRecord', 1)
isFirstRecord = uni.getStorageSync('isFirstRecord');
} ;
return isFirstRecord; return isFirstRecord;
}, },
......
MIT License MIT License
Copyright (c) 2020 www.uviewui.com Copyright (c) 2023 www.uviewui.com
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
...@@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ...@@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
\ No newline at end of file
## 2.0.34(2022-09-25) ## 2.0.36(2023-03-27)
# uView2.0重磅发布,利剑出鞘,一统江湖
1. 重构`deepClone` & `deepMerge`方法
2. 其他优化
## 2.0.34(2022-09-24)
# uView2.0重磅发布,利剑出鞘,一统江湖 # uView2.0重磅发布,利剑出鞘,一统江湖
1. `u-input``u-textarea`增加`ignoreCompositionEvent`属性 1. `u-input``u-textarea`增加`ignoreCompositionEvent`属性
......
...@@ -114,7 +114,7 @@ ...@@ -114,7 +114,7 @@
* @event {Function} confirm 点击确认按钮时触发 * @event {Function} confirm 点击确认按钮时触发
* @event {Function} cancel 点击取消按钮时触发 * @event {Function} cancel 点击取消按钮时触发
* @event {Function} close 点击遮罩关闭出发,closeOnClickOverlay为true有效 * @event {Function} close 点击遮罩关闭出发,closeOnClickOverlay为true有效
* @example <u-loadmore :status="status" icon-type="iconType" load-text="loadText" /> * @example <u-modal :show="true" title="title" content="content"></u-modal>
*/ */
export default { export default {
name: 'u-modal', name: 'u-modal',
...@@ -146,7 +146,7 @@ ...@@ -146,7 +146,7 @@
}, },
// 点击遮罩 // 点击遮罩
// 从原理上来说,modal的遮罩点击,并不是真的点击到了遮罩 // 从原理上来说,modal的遮罩点击,并不是真的点击到了遮罩
// 因为modal依赖于popup的中部弹窗类型,中部弹窗比较特殊,虽有然遮罩,但是为了让弹窗内容能flex居中 // 因为modal依赖于popup的中部弹窗类型,中部弹窗比较特殊,虽然有遮罩,但是为了让弹窗内容能flex居中
// 多了一个透明的遮罩,此透明的遮罩会覆盖在灰色的遮罩上,所以实际上是点击不到灰色遮罩的,popup内部在 // 多了一个透明的遮罩,此透明的遮罩会覆盖在灰色的遮罩上,所以实际上是点击不到灰色遮罩的,popup内部在
// 透明遮罩的子元素做了.stop处理,所以点击内容区,也不会导致误触发 // 透明遮罩的子元素做了.stop处理,所以点击内容区,也不会导致误触发
clickHandler() { clickHandler() {
......
...@@ -83,7 +83,7 @@ export default { ...@@ -83,7 +83,7 @@ export default {
}, },
// 文字装饰,下划线,中划线等,可选值 none|underline|line-through // 文字装饰,下划线,中划线等,可选值 none|underline|line-through
decoration: { decoration: {
tepe: String, type: String,
default: uni.$u.props.text.decoration default: uni.$u.props.text.decoration
}, },
// 外边距,对象、字符串,数值形式均可 // 外边距,对象、字符串,数值形式均可
......
// 此版本发布于2022-00-24 // 此版本发布于2023-03-27
const version = '2.0.34' const version = '2.0.36'
// 开发环境才提示,生产环境不会提示 // 开发环境才提示,生产环境不会提示
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
......
import test from './test.js' import test from './test.js'
import { round } from './digit.js' import { round } from './digit.js'
/** /**
* @description 如果value小于min,取min;如果value大于max,取max * @description 如果value小于min,取min;如果value大于max,取max
* @param {number} min * @param {number} min
* @param {number} max * @param {number} max
* @param {number} value * @param {number} value
*/ */
function range(min = 0, max = 0, value = 0) { function range(min = 0, max = 0, value = 0) {
return Math.max(min, Math.min(max, Number(value))) return Math.max(min, Math.min(max, Number(value)))
} }
/** /**
* @description 用于获取用户传递值的px值 如果用户传递了"xxpx"或者"xxrpx",取出其数值部分,如果是"xxxrpx"还需要用过uni.upx2px进行转换 * @description 用于获取用户传递值的px值 如果用户传递了"xxpx"或者"xxrpx",取出其数值部分,如果是"xxxrpx"还需要用过uni.upx2px进行转换
* @param {number|string} value 用户传递值的px值 * @param {number|string} value 用户传递值的px值
* @param {boolean} unit * @param {boolean} unit
* @returns {number|string} * @returns {number|string}
*/ */
function getPx(value, unit = false) { function getPx(value, unit = false) {
if (test.number(value)) { if (test.number(value)) {
return unit ? `${value}px` : Number(value) return unit ? `${value}px` : Number(value)
} }
// 如果带有rpx,先取出其数值部分,再转为px值 // 如果带有rpx,先取出其数值部分,再转为px值
if (/(rpx|upx)$/.test(value)) { if (/(rpx|upx)$/.test(value)) {
return unit ? `${uni.upx2px(parseInt(value))}px` : Number(uni.upx2px(parseInt(value))) return unit ? `${uni.upx2px(parseInt(value))}px` : Number(uni.upx2px(parseInt(value)))
} }
return unit ? `${parseInt(value)}px` : parseInt(value) return unit ? `${parseInt(value)}px` : parseInt(value)
} }
/** /**
* @description 进行延时,以达到可以简写代码的目的 比如: await uni.$u.sleep(20)将会阻塞20ms * @description 进行延时,以达到可以简写代码的目的 比如: await uni.$u.sleep(20)将会阻塞20ms
* @param {number} value 堵塞时间 单位ms 毫秒 * @param {number} value 堵塞时间 单位ms 毫秒
* @returns {Promise} 返回promise * @returns {Promise} 返回promise
*/ */
function sleep(value = 30) { function sleep(value = 30) {
return new Promise((resolve) => { return new Promise((resolve) => {
setTimeout(() => { setTimeout(() => {
resolve() resolve()
}, value) }, value)
}) })
} }
/** /**
* @description 运行期判断平台 * @description 运行期判断平台
* @returns {string} 返回所在平台(小写) * @returns {string} 返回所在平台(小写)
* @link 运行期判断平台 https://uniapp.dcloud.io/frame?id=判断平台 * @link 运行期判断平台 https://uniapp.dcloud.io/frame?id=判断平台
*/ */
function os() { function os() {
return uni.getSystemInfoSync().platform.toLowerCase() return uni.getSystemInfoSync().platform.toLowerCase()
} }
/** /**
* @description 获取系统信息同步接口 * @description 获取系统信息同步接口
* @link 获取系统信息同步接口 https://uniapp.dcloud.io/api/system/info?id=getsysteminfosync * @link 获取系统信息同步接口 https://uniapp.dcloud.io/api/system/info?id=getsysteminfosync
*/ */
function sys() { function sys() {
return uni.getSystemInfoSync() return uni.getSystemInfoSync()
} }
/** /**
* @description 取一个区间数 * @description 取一个区间数
* @param {Number} min 最小值 * @param {Number} min 最小值
* @param {Number} max 最大值 * @param {Number} max 最大值
*/ */
function random(min, max) { function random(min, max) {
if (min >= 0 && max > 0 && max >= min) { if (min >= 0 && max > 0 && max >= min) {
const gab = max - min + 1 const gab = max - min + 1
return Math.floor(Math.random() * gab + min) return Math.floor(Math.random() * gab + min)
} }
return 0 return 0
} }
/** /**
* @param {Number} len uuid的长度 * @param {Number} len uuid的长度
* @param {Boolean} firstU 将返回的首字母置为"u" * @param {Boolean} firstU 将返回的首字母置为"u"
* @param {Nubmer} radix 生成uuid的基数(意味着返回的字符串都是这个基数),2-二进制,8-八进制,10-十进制,16-十六进制 * @param {Nubmer} radix 生成uuid的基数(意味着返回的字符串都是这个基数),2-二进制,8-八进制,10-十进制,16-十六进制
*/ */
function guid(len = 32, firstU = true, radix = null) { function guid(len = 32, firstU = true, radix = null) {
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('') const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
const uuid = [] const uuid = []
radix = radix || chars.length radix = radix || chars.length
if (len) { if (len) {
// 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位 // 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位
for (let i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix] for (let i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
} else { } else {
let r let r
// rfc4122标准要求返回的uuid中,某些位为固定的字符 // rfc4122标准要求返回的uuid中,某些位为固定的字符
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-' uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
uuid[14] = '4' uuid[14] = '4'
for (let i = 0; i < 36; i++) { for (let i = 0; i < 36; i++) {
if (!uuid[i]) { if (!uuid[i]) {
r = 0 | Math.random() * 16 r = 0 | Math.random() * 16
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r] uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]
} }
} }
} }
// 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class // 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class
if (firstU) { if (firstU) {
uuid.shift() uuid.shift()
return `u${uuid.join('')}` return `u${uuid.join('')}`
} }
return uuid.join('') return uuid.join('')
} }
/** /**
* @description 获取父组件的参数,因为支付宝小程序不支持provide/inject的写法 * @description 获取父组件的参数,因为支付宝小程序不支持provide/inject的写法
this.$parent在非H5中,可以准确获取到父组件,但是在H5中,需要多次this.$parent.$parent.xxx this.$parent在非H5中,可以准确获取到父组件,但是在H5中,需要多次this.$parent.$parent.xxx
这里默认值等于undefined有它的含义,因为最顶层元素(组件)的$parent就是undefined,意味着不传name 这里默认值等于undefined有它的含义,因为最顶层元素(组件)的$parent就是undefined,意味着不传name
值(默认为undefined),就是查找最顶层的$parent 值(默认为undefined),就是查找最顶层的$parent
* @param {string|undefined} name 父组件的参数名 * @param {string|undefined} name 父组件的参数名
*/ */
function $parent(name = undefined) { function $parent(name = undefined) {
let parent = this.$parent let parent = this.$parent
// 通过while历遍,这里主要是为了H5需要多层解析的问题 // 通过while历遍,这里主要是为了H5需要多层解析的问题
while (parent) { while (parent) {
// 父组件 // 父组件
if (parent.$options && parent.$options.name !== name) { if (parent.$options && parent.$options.name !== name) {
// 如果组件的name不相等,继续上一级寻找 // 如果组件的name不相等,继续上一级寻找
parent = parent.$parent parent = parent.$parent
} else { } else {
return parent return parent
} }
} }
return false return false
} }
/** /**
* @description 样式转换 * @description 样式转换
* 对象转字符串,或者字符串转对象 * 对象转字符串,或者字符串转对象
* @param {object | string} customStyle 需要转换的目标 * @param {object | string} customStyle 需要转换的目标
* @param {String} target 转换的目的,object-转为对象,string-转为字符串 * @param {String} target 转换的目的,object-转为对象,string-转为字符串
* @returns {object|string} * @returns {object|string}
*/ */
function addStyle(customStyle, target = 'object') { function addStyle(customStyle, target = 'object') {
// 字符串转字符串,对象转对象情形,直接返回 // 字符串转字符串,对象转对象情形,直接返回
if (test.empty(customStyle) || typeof(customStyle) === 'object' && target === 'object' || target === 'string' && if (test.empty(customStyle) || typeof(customStyle) === 'object' && target === 'object' || target === 'string' &&
typeof(customStyle) === 'string') { typeof(customStyle) === 'string') {
return customStyle return customStyle
} }
// 字符串转对象 // 字符串转对象
if (target === 'object') { if (target === 'object') {
// 去除字符串样式中的两端空格(中间的空格不能去掉,比如padding: 20px 0如果去掉了就错了),空格是无用的 // 去除字符串样式中的两端空格(中间的空格不能去掉,比如padding: 20px 0如果去掉了就错了),空格是无用的
customStyle = trim(customStyle) customStyle = trim(customStyle)
// 根据";"将字符串转为数组形式 // 根据";"将字符串转为数组形式
const styleArray = customStyle.split(';') const styleArray = customStyle.split(';')
const style = {} const style = {}
// 历遍数组,拼接成对象 // 历遍数组,拼接成对象
for (let i = 0; i < styleArray.length; i++) { for (let i = 0; i < styleArray.length; i++) {
// 'font-size:20px;color:red;',如此最后字符串有";"的话,会导致styleArray最后一个元素为空字符串,这里需要过滤 // 'font-size:20px;color:red;',如此最后字符串有";"的话,会导致styleArray最后一个元素为空字符串,这里需要过滤
if (styleArray[i]) { if (styleArray[i]) {
const item = styleArray[i].split(':') const item = styleArray[i].split(':')
style[trim(item[0])] = trim(item[1]) style[trim(item[0])] = trim(item[1])
} }
} }
return style return style
} }
// 这里为对象转字符串形式 // 这里为对象转字符串形式
let string = '' let string = ''
for (const i in customStyle) { for (const i in customStyle) {
// 驼峰转为中划线的形式,否则css内联样式,无法识别驼峰样式属性名 // 驼峰转为中划线的形式,否则css内联样式,无法识别驼峰样式属性名
const key = i.replace(/([A-Z])/g, '-$1').toLowerCase() const key = i.replace(/([A-Z])/g, '-$1').toLowerCase()
string += `${key}:${customStyle[i]};` string += `${key}:${customStyle[i]};`
} }
// 去除两端空格 // 去除两端空格
return trim(string) return trim(string)
} }
/** /**
* @description 添加单位,如果有rpx,upx,%,px等单位结尾或者值为auto,直接返回,否则加上px单位结尾 * @description 添加单位,如果有rpx,upx,%,px等单位结尾或者值为auto,直接返回,否则加上px单位结尾
* @param {string|number} value 需要添加单位的值 * @param {string|number} value 需要添加单位的值
* @param {string} unit 添加的单位名 比如px * @param {string} unit 添加的单位名 比如px
*/ */
function addUnit(value = 'auto', unit = uni?.$u?.config?.unit ?? 'px') { function addUnit(value = 'auto', unit = uni?.$u?.config?.unit ?? 'px') {
value = String(value) value = String(value)
// 用uView内置验证规则中的number判断是否为数值 // 用uView内置验证规则中的number判断是否为数值
return test.number(value) ? `${value}${unit}` : value return test.number(value) ? `${value}${unit}` : value
} }
/** /**
* @description 深度克隆 * @description 深度克隆
* @param {object} obj 需要深度克隆的对象 * @param {object} obj 需要深度克隆的对象
* @returns {*} 克隆后的对象或者原值(不是对象) * @param cache 缓存
*/ * @returns {*} 克隆后的对象或者原值(不是对象)
function deepClone(obj) { */
// 对常见的“非”值,直接返回原来值 function deepClone(obj, cache = new WeakMap()) {
if ([null, undefined, NaN, false].includes(obj)) return obj if (obj === null || typeof obj !== 'object') return obj;
if (typeof obj !== 'object' && typeof obj !== 'function') { if (cache.has(obj)) return cache.get(obj);
// 原始类型直接返回 let clone;
return obj if (obj instanceof Date) {
} clone = new Date(obj.getTime());
const o = test.array(obj) ? [] : {} } else if (obj instanceof RegExp) {
for (const i in obj) { clone = new RegExp(obj);
if (obj.hasOwnProperty(i)) { } else if (obj instanceof Map) {
o[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i] clone = new Map(Array.from(obj, ([key, value]) => [key, deepClone(value, cache)]));
} } else if (obj instanceof Set) {
} clone = new Set(Array.from(obj, value => deepClone(value, cache)));
return o } else if (Array.isArray(obj)) {
} clone = obj.map(value => deepClone(value, cache));
} else if (Object.prototype.toString.call(obj) === '[object Object]') {
/** clone = Object.create(Object.getPrototypeOf(obj));
* @description JS对象深度合并 cache.set(obj, clone);
* @param {object} target 需要拷贝的对象 for (const [key, value] of Object.entries(obj)) {
* @param {object} source 拷贝的来源对象 clone[key] = deepClone(value, cache);
* @returns {object|boolean} 深度合并后的对象或者false(入参有不是对象) }
*/ } else {
function deepMerge(target = {}, source = {}) { clone = Object.assign({}, obj);
target = deepClone(target) }
if (typeof target !== 'object' || typeof source !== 'object') return false cache.set(obj, clone);
for (const prop in source) { return clone;
if (!source.hasOwnProperty(prop)) continue }
if (prop in target) {
if (typeof target[prop] !== 'object') { /**
target[prop] = source[prop] * @description JS对象深度合并
} else if (typeof source[prop] !== 'object') { * @param {object} target 需要拷贝的对象
target[prop] = source[prop] * @param {object} source 拷贝的来源对象
} else if (target[prop].concat && source[prop].concat) { * @returns {object|boolean} 深度合并后的对象或者false(入参有不是对象)
target[prop] = target[prop].concat(source[prop]) */
} else { function deepMerge(target = {}, source = {}) {
target[prop] = deepMerge(target[prop], source[prop]) target = deepClone(target)
} if (typeof target !== 'object' || target === null || typeof source !== 'object' || source === null) return target;
} else { const merged = Array.isArray(target) ? target.slice() : Object.assign({}, target);
target[prop] = source[prop] for (const prop in source) {
} if (!source.hasOwnProperty(prop)) continue;
} const sourceValue = source[prop];
return target const targetValue = merged[prop];
} if (sourceValue instanceof Date) {
merged[prop] = new Date(sourceValue);
/** } else if (sourceValue instanceof RegExp) {
* @description error提示 merged[prop] = new RegExp(sourceValue);
* @param {*} err 错误内容 } else if (sourceValue instanceof Map) {
*/ merged[prop] = new Map(sourceValue);
function error(err) { } else if (sourceValue instanceof Set) {
// 开发环境才提示,生产环境不会提示 merged[prop] = new Set(sourceValue);
if (process.env.NODE_ENV === 'development') { } else if (typeof sourceValue === 'object' && sourceValue !== null) {
console.error(`uView提示:${err}`) merged[prop] = deepMerge(targetValue, sourceValue);
} } else {
} merged[prop] = sourceValue;
}
/** }
* @description 打乱数组 return merged;
* @param {array} array 需要打乱的数组 }
* @returns {array} 打乱后的数组
*/ /**
function randomArray(array = []) { * @description error提示
// 原理是sort排序,Math.random()产生0<= x < 1之间的数,会导致x-0.05大于或者小于0 * @param {*} err 错误内容
return array.sort(() => Math.random() - 0.5) */
} function error(err) {
// 开发环境才提示,生产环境不会提示
// padStart 的 polyfill,因为某些机型或情况,还无法支持es7的padStart,比如电脑版的微信小程序 if (process.env.NODE_ENV === 'development') {
// 所以这里做一个兼容polyfill的兼容处理 console.error(`uView提示:${err}`)
if (!String.prototype.padStart) { }
// 为了方便表示这里 fillString 用了ES6 的默认参数,不影响理解 }
String.prototype.padStart = function(maxLength, fillString = ' ') {
if (Object.prototype.toString.call(fillString) !== '[object String]') { /**
throw new TypeError( * @description 打乱数组
'fillString must be String' * @param {array} array 需要打乱的数组
) * @returns {array} 打乱后的数组
} */
const str = this function randomArray(array = []) {
// 返回 String(str) 这里是为了使返回的值是字符串字面量,在控制台中更符合直觉 // 原理是sort排序,Math.random()产生0<= x < 1之间的数,会导致x-0.05大于或者小于0
if (str.length >= maxLength) return String(str) return array.sort(() => Math.random() - 0.5)
}
const fillLength = maxLength - str.length
let times = Math.ceil(fillLength / fillString.length) // padStart 的 polyfill,因为某些机型或情况,还无法支持es7的padStart,比如电脑版的微信小程序
while (times >>= 1) { // 所以这里做一个兼容polyfill的兼容处理
fillString += fillString if (!String.prototype.padStart) {
if (times === 1) { // 为了方便表示这里 fillString 用了ES6 的默认参数,不影响理解
fillString += fillString String.prototype.padStart = function(maxLength, fillString = ' ') {
} if (Object.prototype.toString.call(fillString) !== '[object String]') {
} throw new TypeError(
return fillString.slice(0, fillLength) + str 'fillString must be String'
} )
} }
const str = this
/** // 返回 String(str) 这里是为了使返回的值是字符串字面量,在控制台中更符合直觉
* @description 格式化时间 if (str.length >= maxLength) return String(str)
* @param {String|Number} dateTime 需要格式化的时间戳
* @param {String} fmt 格式化规则 yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合 默认yyyy-mm-dd const fillLength = maxLength - str.length
* @returns {string} 返回格式化后的字符串 let times = Math.ceil(fillLength / fillString.length)
*/ while (times >>= 1) {
function timeFormat(dateTime = null, formatStr = 'yyyy-mm-dd') { fillString += fillString
let date if (times === 1) {
// 若传入时间为假值,则取当前时间 fillString += fillString
if (!dateTime) { }
date = new Date() }
} return fillString.slice(0, fillLength) + str
// 若为unix秒时间戳,则转为毫秒时间戳(逻辑有点奇怪,但不敢改,以保证历史兼容) }
else if (/^\d{10}$/.test(dateTime?.toString().trim())) { }
date = new Date(dateTime * 1000)
} /**
// 若用户传入字符串格式时间戳,new Date无法解析,需做兼容 * @description 格式化时间
else if (typeof dateTime === 'string' && /^\d+$/.test(dateTime.trim())) { * @param {String|Number} dateTime 需要格式化的时间戳
date = new Date(Number(dateTime)) * @param {String} fmt 格式化规则 yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合 默认yyyy-mm-dd
} * @returns {string} 返回格式化后的字符串
// 处理平台性差异,在Safari/Webkit中,new Date仅支持/作为分割符的字符串时间 */
// 处理 '2022-07-10 01:02:03',跳过 '2022-07-10T01:02:03' function timeFormat(dateTime = null, formatStr = 'yyyy-mm-dd') {
else if (typeof dateTime === 'string' && dateTime.includes('-') && !dateTime.includes('T')) { let date
date = new Date(dateTime.replace(/-/g, '/')) // 若传入时间为假值,则取当前时间
} if (!dateTime) {
// 其他都认为符合 RFC 2822 规范 date = new Date()
else { }
date = new Date(dateTime) // 若为unix秒时间戳,则转为毫秒时间戳(逻辑有点奇怪,但不敢改,以保证历史兼容)
} else if (/^\d{10}$/.test(dateTime?.toString().trim())) {
date = new Date(dateTime * 1000)
const timeSource = { }
'y': date.getFullYear().toString(), // 年 // 若用户传入字符串格式时间戳,new Date无法解析,需做兼容
'm': (date.getMonth() + 1).toString().padStart(2, '0'), // 月 else if (typeof dateTime === 'string' && /^\d+$/.test(dateTime.trim())) {
'd': date.getDate().toString().padStart(2, '0'), // 日 date = new Date(Number(dateTime))
'h': date.getHours().toString().padStart(2, '0'), // 时 }
'M': date.getMinutes().toString().padStart(2, '0'), // 分 // 处理平台性差异,在Safari/Webkit中,new Date仅支持/作为分割符的字符串时间
's': date.getSeconds().toString().padStart(2, '0') // 秒 // 处理 '2022-07-10 01:02:03',跳过 '2022-07-10T01:02:03'
// 有其他格式化字符需求可以继续添加,必须转化成字符串 else if (typeof dateTime === 'string' && dateTime.includes('-') && !dateTime.includes('T')) {
} date = new Date(dateTime.replace(/-/g, '/'))
}
for (const key in timeSource) { // 其他都认为符合 RFC 2822 规范
const [ret] = new RegExp(`${key}+`).exec(formatStr) || [] else {
if (ret) { date = new Date(dateTime)
// 年可能只需展示两位 }
const beginIndex = key === 'y' && ret.length === 2 ? 2 : 0
formatStr = formatStr.replace(ret, timeSource[key].slice(beginIndex)) const timeSource = {
} 'y': date.getFullYear().toString(), // 年
} 'm': (date.getMonth() + 1).toString().padStart(2, '0'), // 月
'd': date.getDate().toString().padStart(2, '0'), // 日
return formatStr 'h': date.getHours().toString().padStart(2, '0'), // 时
} 'M': date.getMinutes().toString().padStart(2, '0'), // 分
's': date.getSeconds().toString().padStart(2, '0') // 秒
/** // 有其他格式化字符需求可以继续添加,必须转化成字符串
* @description 时间戳转为多久之前 }
* @param {String|Number} timestamp 时间戳
* @param {String|Boolean} format for (const key in timeSource) {
* 格式化规则如果为时间格式字符串,超出一定时间范围,返回固定的时间格式; const [ret] = new RegExp(`${key}+`).exec(formatStr) || []
* 如果为布尔值false,无论什么时间,都返回多久以前的格式 if (ret) {
* @returns {string} 转化后的内容 // 年可能只需展示两位
*/ const beginIndex = key === 'y' && ret.length === 2 ? 2 : 0
function timeFrom(timestamp = null, format = 'yyyy-mm-dd') { formatStr = formatStr.replace(ret, timeSource[key].slice(beginIndex))
if (timestamp == null) timestamp = Number(new Date()) }
timestamp = parseInt(timestamp) }
// 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
if (timestamp.toString().length == 10) timestamp *= 1000 return formatStr
let timer = (new Date()).getTime() - timestamp }
timer = parseInt(timer / 1000)
// 如果小于5分钟,则返回"刚刚",其他以此类推 /**
let tips = '' * @description 时间戳转为多久之前
switch (true) { * @param {String|Number} timestamp 时间戳
case timer < 300: * @param {String|Boolean} format
tips = '刚刚' * 格式化规则如果为时间格式字符串,超出一定时间范围,返回固定的时间格式;
break * 如果为布尔值false,无论什么时间,都返回多久以前的格式
case timer >= 300 && timer < 3600: * @returns {string} 转化后的内容
tips = `${parseInt(timer / 60)}分钟前` */
break function timeFrom(timestamp = null, format = 'yyyy-mm-dd') {
case timer >= 3600 && timer < 86400: if (timestamp == null) timestamp = Number(new Date())
tips = `${parseInt(timer / 3600)}小时前` timestamp = parseInt(timestamp)
break // 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
case timer >= 86400 && timer < 2592000: if (timestamp.toString().length == 10) timestamp *= 1000
tips = `${parseInt(timer / 86400)}天前` let timer = (new Date()).getTime() - timestamp
break timer = parseInt(timer / 1000)
default: // 如果小于5分钟,则返回"刚刚",其他以此类推
// 如果format为false,则无论什么时间戳,都显示xx之前 let tips = ''
if (format === false) { switch (true) {
if (timer >= 2592000 && timer < 365 * 86400) { case timer < 300:
tips = `${parseInt(timer / (86400 * 30))}个月前` tips = '刚刚'
} else { break
tips = `${parseInt(timer / (86400 * 365))}年前` case timer >= 300 && timer < 3600:
} tips = `${parseInt(timer / 60)}分钟前`
} else { break
tips = timeFormat(timestamp, format) case timer >= 3600 && timer < 86400:
} tips = `${parseInt(timer / 3600)}小时前`
} break
return tips case timer >= 86400 && timer < 2592000:
} tips = `${parseInt(timer / 86400)}天前`
break
/** default:
* @description 去除空格 // 如果format为false,则无论什么时间戳,都显示xx之前
* @param String str 需要去除空格的字符串 if (format === false) {
* @param String pos both(左右)|left|right|all 默认both if (timer >= 2592000 && timer < 365 * 86400) {
*/ tips = `${parseInt(timer / (86400 * 30))}个月前`
function trim(str, pos = 'both') { } else {
str = String(str) tips = `${parseInt(timer / (86400 * 365))}年前`
if (pos == 'both') { }
return str.replace(/^\s+|\s+$/g, '') } else {
} tips = timeFormat(timestamp, format)
if (pos == 'left') { }
return str.replace(/^\s*/, '') }
} return tips
if (pos == 'right') { }
return str.replace(/(\s*$)/g, '')
} /**
if (pos == 'all') { * @description 去除空格
return str.replace(/\s+/g, '') * @param String str 需要去除空格的字符串
} * @param String pos both(左右)|left|right|all 默认both
return str */
} function trim(str, pos = 'both') {
str = String(str)
/** if (pos == 'both') {
* @description 对象转url参数 return str.replace(/^\s+|\s+$/g, '')
* @param {object} data,对象 }
* @param {Boolean} isPrefix,是否自动加上"?" if (pos == 'left') {
* @param {string} arrayFormat 规则 indices|brackets|repeat|comma return str.replace(/^\s*/, '')
*/ }
function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') { if (pos == 'right') {
const prefix = isPrefix ? '?' : '' return str.replace(/(\s*$)/g, '')
const _result = [] }
if (['indices', 'brackets', 'repeat', 'comma'].indexOf(arrayFormat) == -1) arrayFormat = 'brackets' if (pos == 'all') {
for (const key in data) { return str.replace(/\s+/g, '')
const value = data[key] }
// 去掉为空的参数 return str
if (['', undefined, null].indexOf(value) >= 0) { }
continue
} /**
// 如果值为数组,另行处理 * @description 对象转url参数
if (value.constructor === Array) { * @param {object} data,对象
// e.g. {ids: [1, 2, 3]} * @param {Boolean} isPrefix,是否自动加上"?"
switch (arrayFormat) { * @param {string} arrayFormat 规则 indices|brackets|repeat|comma
case 'indices': */
// 结果: ids[0]=1&ids[1]=2&ids[2]=3 function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') {
for (let i = 0; i < value.length; i++) { const prefix = isPrefix ? '?' : ''
_result.push(`${key}[${i}]=${value[i]}`) const _result = []
} if (['indices', 'brackets', 'repeat', 'comma'].indexOf(arrayFormat) == -1) arrayFormat = 'brackets'
break for (const key in data) {
case 'brackets': const value = data[key]
// 结果: ids[]=1&ids[]=2&ids[]=3 // 去掉为空的参数
value.forEach((_value) => { if (['', undefined, null].indexOf(value) >= 0) {
_result.push(`${key}[]=${_value}`) continue
}) }
break // 如果值为数组,另行处理
case 'repeat': if (value.constructor === Array) {
// 结果: ids=1&ids=2&ids=3 // e.g. {ids: [1, 2, 3]}
value.forEach((_value) => { switch (arrayFormat) {
_result.push(`${key}=${_value}`) case 'indices':
}) // 结果: ids[0]=1&ids[1]=2&ids[2]=3
break for (let i = 0; i < value.length; i++) {
case 'comma': _result.push(`${key}[${i}]=${value[i]}`)
// 结果: ids=1,2,3 }
let commaStr = '' break
value.forEach((_value) => { case 'brackets':
commaStr += (commaStr ? ',' : '') + _value // 结果: ids[]=1&ids[]=2&ids[]=3
}) value.forEach((_value) => {
_result.push(`${key}=${commaStr}`) _result.push(`${key}[]=${_value}`)
break })
default: break
value.forEach((_value) => { case 'repeat':
_result.push(`${key}[]=${_value}`) // 结果: ids=1&ids=2&ids=3
}) value.forEach((_value) => {
} _result.push(`${key}=${_value}`)
} else { })
_result.push(`${key}=${value}`) break
} case 'comma':
} // 结果: ids=1,2,3
return _result.length ? prefix + _result.join('&') : '' let commaStr = ''
} value.forEach((_value) => {
commaStr += (commaStr ? ',' : '') + _value
/** })
* 显示消息提示框 _result.push(`${key}=${commaStr}`)
* @param {String} title 提示的内容,长度与 icon 取值有关。 break
* @param {Number} duration 提示的延迟时间,单位毫秒,默认:2000 default:
*/ value.forEach((_value) => {
function toast(title, duration = 2000) { _result.push(`${key}[]=${_value}`)
uni.showToast({ })
title: String(title), }
icon: 'none', } else {
duration _result.push(`${key}=${value}`)
}) }
} }
return _result.length ? prefix + _result.join('&') : ''
/** }
* @description 根据主题type值,获取对应的图标
* @param {String} type 主题名称,primary|info|error|warning|success /**
* @param {boolean} fill 是否使用fill填充实体的图标 * 显示消息提示框
*/ * @param {String} title 提示的内容,长度与 icon 取值有关。
function type2icon(type = 'success', fill = false) { * @param {Number} duration 提示的延迟时间,单位毫秒,默认:2000
// 如果非预置值,默认为success */
if (['primary', 'info', 'error', 'warning', 'success'].indexOf(type) == -1) type = 'success' function toast(title, duration = 2000) {
let iconName = '' uni.showToast({
// 目前(2019-12-12),info和primary使用同一个图标 title: String(title),
switch (type) { icon: 'none',
case 'primary': duration
iconName = 'info-circle' })
break }
case 'info':
iconName = 'info-circle' /**
break * @description 根据主题type值,获取对应的图标
case 'error': * @param {String} type 主题名称,primary|info|error|warning|success
iconName = 'close-circle' * @param {boolean} fill 是否使用fill填充实体的图标
break */
case 'warning': function type2icon(type = 'success', fill = false) {
iconName = 'error-circle' // 如果非预置值,默认为success
break if (['primary', 'info', 'error', 'warning', 'success'].indexOf(type) == -1) type = 'success'
case 'success': let iconName = ''
iconName = 'checkmark-circle' // 目前(2019-12-12),info和primary使用同一个图标
break switch (type) {
default: case 'primary':
iconName = 'checkmark-circle' iconName = 'info-circle'
} break
// 是否是实体类型,加上-fill,在icon组件库中,实体的类名是后面加-fill的 case 'info':
if (fill) iconName += '-fill' iconName = 'info-circle'
return iconName break
} case 'error':
iconName = 'close-circle'
/** break
* @description 数字格式化 case 'warning':
* @param {number|string} number 要格式化的数字 iconName = 'error-circle'
* @param {number} decimals 保留几位小数 break
* @param {string} decimalPoint 小数点符号 case 'success':
* @param {string} thousandsSeparator 千分位符号 iconName = 'checkmark-circle'
* @returns {string} 格式化后的数字 break
*/ default:
function priceFormat(number, decimals = 0, decimalPoint = '.', thousandsSeparator = ',') { iconName = 'checkmark-circle'
number = (`${number}`).replace(/[^0-9+-Ee.]/g, '') }
const n = !isFinite(+number) ? 0 : +number // 是否是实体类型,加上-fill,在icon组件库中,实体的类名是后面加-fill的
const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals) if (fill) iconName += '-fill'
const sep = (typeof thousandsSeparator === 'undefined') ? ',' : thousandsSeparator return iconName
const dec = (typeof decimalPoint === 'undefined') ? '.' : decimalPoint }
let s = ''
/**
s = (prec ? round(n, prec) + '' : `${Math.round(n)}`).split('.') * @description 数字格式化
const re = /(-?\d+)(\d{3})/ * @param {number|string} number 要格式化的数字
while (re.test(s[0])) { * @param {number} decimals 保留几位小数
s[0] = s[0].replace(re, `$1${sep}$2`) * @param {string} decimalPoint 小数点符号
} * @param {string} thousandsSeparator 千分位符号
* @returns {string} 格式化后的数字
if ((s[1] || '').length < prec) { */
s[1] = s[1] || '' function priceFormat(number, decimals = 0, decimalPoint = '.', thousandsSeparator = ',') {
s[1] += new Array(prec - s[1].length + 1).join('0') number = (`${number}`).replace(/[^0-9+-Ee.]/g, '')
} const n = !isFinite(+number) ? 0 : +number
return s.join(dec) const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
} const sep = (typeof thousandsSeparator === 'undefined') ? ',' : thousandsSeparator
const dec = (typeof decimalPoint === 'undefined') ? '.' : decimalPoint
/** let s = ''
* @description 获取duration值
* 如果带有ms或者s直接返回,如果大于一定值,认为是ms单位,小于一定值,认为是s单位 s = (prec ? round(n, prec) + '' : `${Math.round(n)}`).split('.')
* 比如以30位阈值,那么300大于30,可以理解为用户想要的是300ms,而不是想花300s去执行一个动画 const re = /(-?\d+)(\d{3})/
* @param {String|number} value 比如: "1s"|"100ms"|1|100 while (re.test(s[0])) {
* @param {boolean} unit 提示: 如果是false 默认返回number s[0] = s[0].replace(re, `$1${sep}$2`)
* @return {string|number} }
*/
function getDuration(value, unit = true) { if ((s[1] || '').length < prec) {
const valueNum = parseInt(value) s[1] = s[1] || ''
if (unit) { s[1] += new Array(prec - s[1].length + 1).join('0')
if (/s$/.test(value)) return value }
return value > 30 ? `${value}ms` : `${value}s` return s.join(dec)
} }
if (/ms$/.test(value)) return valueNum
if (/s$/.test(value)) return valueNum > 30 ? valueNum : valueNum * 1000 /**
return valueNum * @description 获取duration值
} * 如果带有ms或者s直接返回,如果大于一定值,认为是ms单位,小于一定值,认为是s单位
* 比如以30位阈值,那么300大于30,可以理解为用户想要的是300ms,而不是想花300s去执行一个动画
/** * @param {String|number} value 比如: "1s"|"100ms"|1|100
* @description 日期的月或日补零操作 * @param {boolean} unit 提示: 如果是false 默认返回number
* @param {String} value 需要补零的值 * @return {string|number}
*/ */
function padZero(value) { function getDuration(value, unit = true) {
return `00${value}`.slice(-2) const valueNum = parseInt(value)
} if (unit) {
if (/s$/.test(value)) return value
/** return value > 30 ? `${value}ms` : `${value}s`
* @description 在u-form的子组件内容发生变化,或者失去焦点时,尝试通知u-form执行校验方法 }
* @param {*} instance if (/ms$/.test(value)) return valueNum
* @param {*} event if (/s$/.test(value)) return valueNum > 30 ? valueNum : valueNum * 1000
*/ return valueNum
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方法 * @description 日期的月或日补零操作
// 同时将form-item的pros传递给form,让其进行精确对象验证 * @param {String} value 需要补零的值
if (formItem && form) { */
form.validateField(formItem.prop, () => {}, event) function padZero(value) {
} return `00${value}`.slice(-2)
} }
/** /**
* @description 获取某个对象下的属性,用于通过类似'a.b.c'的形式去获取一个对象的的属性的形式 * @description 在u-form的子组件内容发生变化,或者失去焦点时,尝试通知u-form执行校验方法
* @param {object} obj 对象 * @param {*} instance
* @param {string} key 需要获取的属性字段 * @param {*} event
* @returns {*} */
*/ function formValidate(instance, event) {
function getProperty(obj, key) { const formItem = uni.$u.$parent.call(instance, 'u-form-item')
if (!obj) { const form = uni.$u.$parent.call(instance, 'u-form')
return // 如果发生变化的input或者textarea等,其父组件中有u-form-item或者u-form等,就执行form的validate方法
} // 同时将form-item的pros传递给form,让其进行精确对象验证
if (typeof key !== 'string' || key === '') { if (formItem && form) {
return '' form.validateField(formItem.prop, () => {}, event)
} }
if (key.indexOf('.') !== -1) { }
const keys = key.split('.')
let firstObj = obj[keys[0]] || {} /**
* @description 获取某个对象下的属性,用于通过类似'a.b.c'的形式去获取一个对象的的属性的形式
for (let i = 1; i < keys.length; i++) { * @param {object} obj 对象
if (firstObj) { * @param {string} key 需要获取的属性字段
firstObj = firstObj[keys[i]] * @returns {*}
} */
} function getProperty(obj, key) {
return firstObj if (!obj) {
} return
return obj[key] }
} if (typeof key !== 'string' || key === '') {
return ''
/** }
* @description 设置对象的属性值,如果'a.b.c'的形式进行设置 if (key.indexOf('.') !== -1) {
* @param {object} obj 对象 const keys = key.split('.')
* @param {string} key 需要设置的属性 let firstObj = obj[keys[0]] || {}
* @param {string} value 设置的值
*/ for (let i = 1; i < keys.length; i++) {
function setProperty(obj, key, value) { if (firstObj) {
if (!obj) { firstObj = firstObj[keys[i]]
return }
} }
// 递归赋值 return firstObj
const inFn = function(_obj, keys, v) { }
// 最后一个属性key return obj[key]
if (keys.length === 1) { }
_obj[keys[0]] = v
return /**
} * @description 设置对象的属性值,如果'a.b.c'的形式进行设置
// 0~length-1个key * @param {object} obj 对象
while (keys.length > 1) { * @param {string} key 需要设置的属性
const k = keys[0] * @param {string} value 设置的值
if (!_obj[k] || (typeof _obj[k] !== 'object')) { */
_obj[k] = {} function setProperty(obj, key, value) {
} if (!obj) {
const key = keys.shift() return
// 自调用判断是否存在属性,不存在则自动创建对象 }
inFn(_obj[k], keys, v) // 递归赋值
} const inFn = function(_obj, keys, v) {
} // 最后一个属性key
if (keys.length === 1) {
if (typeof key !== 'string' || key === '') { _obj[keys[0]] = v
return
} else if (key.indexOf('.') !== -1) { // 支持多层级赋值操作 }
const keys = key.split('.') // 0~length-1个key
inFn(obj, keys, value) while (keys.length > 1) {
} else { const k = keys[0]
obj[key] = value if (!_obj[k] || (typeof _obj[k] !== 'object')) {
} _obj[k] = {}
} }
const key = keys.shift()
/** // 自调用判断是否存在属性,不存在则自动创建对象
* @description 获取当前页面路径 inFn(_obj[k], keys, v)
*/ }
function page() { }
const pages = getCurrentPages()
// 某些特殊情况下(比如页面进行redirectTo时的一些时机),pages可能为空数组 if (typeof key !== 'string' || key === '') {
return `/${pages[pages.length - 1]?.route ?? ''}`
} } else if (key.indexOf('.') !== -1) { // 支持多层级赋值操作
const keys = key.split('.')
/** inFn(obj, keys, value)
* @description 获取当前路由栈实例数组 } else {
*/ obj[key] = value
function pages() { }
const pages = getCurrentPages() }
return pages
} /**
* @description 获取当前页面路径
/** */
* @description 修改uView内置属性值 function page() {
* @param {object} props 修改内置props属性 const pages = getCurrentPages()
* @param {object} config 修改内置config属性 // 某些特殊情况下(比如页面进行redirectTo时的一些时机),pages可能为空数组
* @param {object} color 修改内置color属性 return `/${pages[pages.length - 1]?.route ?? ''}`
* @param {object} zIndex 修改内置zIndex属性 }
*/
function setConfig({ /**
props = {}, * @description 获取当前路由栈实例数组
config = {}, */
color = {}, function pages() {
zIndex = {} const pages = getCurrentPages()
}) { return pages
const { }
deepMerge,
} = uni.$u /**
uni.$u.config = deepMerge(uni.$u.config, config) * 获取页面历史栈指定层实例
uni.$u.props = deepMerge(uni.$u.props, props) * @param back {number} [0] - 0或者负数,表示获取历史栈的哪一层,0表示获取当前页面实例,-1 表示获取上一个页面实例。默认0。
uni.$u.color = deepMerge(uni.$u.color, color) */
uni.$u.zIndex = deepMerge(uni.$u.zIndex, zIndex) function getHistoryPage(back = 0) {
} const pages = getCurrentPages()
const len = pages.length
export default { return pages[len - 1 + back]
range, }
getPx,
sleep, /**
os, * @description 修改uView内置属性值
sys, * @param {object} props 修改内置props属性
random, * @param {object} config 修改内置config属性
guid, * @param {object} color 修改内置color属性
$parent, * @param {object} zIndex 修改内置zIndex属性
addStyle, */
addUnit, function setConfig({
deepClone, props = {},
deepMerge, config = {},
error, color = {},
randomArray, zIndex = {}
timeFormat, }) {
timeFrom, const {
trim, deepMerge,
queryParams, } = uni.$u
toast, uni.$u.config = deepMerge(uni.$u.config, config)
type2icon, uni.$u.props = deepMerge(uni.$u.props, props)
priceFormat, uni.$u.color = deepMerge(uni.$u.color, color)
getDuration, uni.$u.zIndex = deepMerge(uni.$u.zIndex, zIndex)
padZero, }
formValidate,
getProperty, export default {
setProperty, range,
page, getPx,
pages, sleep,
setConfig 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,
getHistoryPage,
setConfig
}
...@@ -4,121 +4,121 @@ ...@@ -4,121 +4,121 @@
*/ */
class Router { class Router {
constructor() { constructor() {
// 原始属性定义 // 原始属性定义
this.config = { this.config = {
type: 'navigateTo', type: 'navigateTo',
url: '', url: '',
delta: 1, // navigateBack页面后退时,回退的层数 delta: 1, // navigateBack页面后退时,回退的层数
params: {}, // 传递的参数 params: {}, // 传递的参数
animationType: 'pop-in', // 窗口动画,只在APP有效 animationType: 'pop-in', // 窗口动画,只在APP有效
animationDuration: 300, // 窗口动画持续时间,单位毫秒,只在APP有效 animationDuration: 300, // 窗口动画持续时间,单位毫秒,只在APP有效
intercept: false // 是否需要拦截 intercept: false // 是否需要拦截
} }
// 因为route方法是需要对外赋值给另外的对象使用,同时route内部有使用this,会导致route失去上下文 // 因为route方法是需要对外赋值给另外的对象使用,同时route内部有使用this,会导致route失去上下文
// 这里在构造函数中进行this绑定 // 这里在构造函数中进行this绑定
this.route = this.route.bind(this) this.route = this.route.bind(this)
} }
// 判断url前面是否有"/",如果没有则加上,否则无法跳转 // 判断url前面是否有"/",如果没有则加上,否则无法跳转
addRootPath(url) { addRootPath(url) {
return url[0] === '/' ? url : `/${url}` return url[0] === '/' ? url : `/${url}`
} }
// 整合路由参数 // 整合路由参数
mixinParam(url, params) { mixinParam(url, params) {
url = url && this.addRootPath(url) url = url && this.addRootPath(url)
// 使用正则匹配,主要依据是判断是否有"/","?","="等,如“/page/index/index?name=mary" // 使用正则匹配,主要依据是判断是否有"/","?","="等,如“/page/index/index?name=mary"
// 如果有url中有get参数,转换后无需带上"?" // 如果有url中有get参数,转换后无需带上"?"
let query = '' let query = ''
if (/.*\/.*\?.*=.*/.test(url)) { if (/.*\/.*\?.*=.*/.test(url)) {
// object对象转为get类型的参数 // object对象转为get类型的参数
query = uni.$u.queryParams(params, false) query = uni.$u.queryParams(params, false)
// 因为已有get参数,所以后面拼接的参数需要带上"&"隔开 // 因为已有get参数,所以后面拼接的参数需要带上"&"隔开
return url += `&${query}` return url += `&${query}`
} }
// 直接拼接参数,因为此处url中没有后面的query参数,也就没有"?/&"之类的符号 // 直接拼接参数,因为此处url中没有后面的query参数,也就没有"?/&"之类的符号
query = uni.$u.queryParams(params) query = uni.$u.queryParams(params)
return url += query return url += query
} }
// 对外的方法名称 // 对外的方法名称
async route(options = {}, params = {}) { async route(options = {}, params = {}) {
// 合并用户的配置和内部的默认配置 // 合并用户的配置和内部的默认配置
let mergeConfig = {} let mergeConfig = {}
if (typeof options === 'string') { if (typeof options === 'string') {
// 如果options为字符串,则为route(url, params)的形式 // 如果options为字符串,则为route(url, params)的形式
mergeConfig.url = this.mixinParam(options, params) mergeConfig.url = this.mixinParam(options, params)
mergeConfig.type = 'navigateTo' mergeConfig.type = 'navigateTo'
} else { } else {
mergeConfig = uni.$u.deepMerge(options, this.config) mergeConfig = uni.$u.deepMerge(this.config, options)
// 否则正常使用mergeConfig中的url和params进行拼接 // 否则正常使用mergeConfig中的url和params进行拼接
mergeConfig.url = this.mixinParam(options.url, options.params) mergeConfig.url = this.mixinParam(options.url, options.params)
} }
// 如果本次跳转的路径和本页面路径一致,不执行跳转,防止用户快速点击跳转按钮,造成多次跳转同一个页面的问题 // 如果本次跳转的路径和本页面路径一致,不执行跳转,防止用户快速点击跳转按钮,造成多次跳转同一个页面的问题
if (mergeConfig.url === uni.$u.page()) return if (mergeConfig.url === uni.$u.page()) return
if (params.intercept) { if (params.intercept) {
this.config.intercept = params.intercept this.config.intercept = params.intercept
} }
// params参数也带给拦截器 // params参数也带给拦截器
mergeConfig.params = params mergeConfig.params = params
// 合并内外部参数 // 合并内外部参数
mergeConfig = uni.$u.deepMerge(this.config, mergeConfig) mergeConfig = uni.$u.deepMerge(this.config, mergeConfig)
// 判断用户是否定义了拦截器 // 判断用户是否定义了拦截器
if (typeof uni.$u.routeIntercept === 'function') { if (typeof uni.$u.routeIntercept === 'function') {
// 定一个promise,根据用户执行resolve(true)或者resolve(false)来决定是否进行路由跳转 // 定一个promise,根据用户执行resolve(true)或者resolve(false)来决定是否进行路由跳转
const isNext = await new Promise((resolve, reject) => { const isNext = await new Promise((resolve, reject) => {
uni.$u.routeIntercept(mergeConfig, resolve) uni.$u.routeIntercept(mergeConfig, resolve)
}) })
// 如果isNext为true,则执行路由跳转 // 如果isNext为true,则执行路由跳转
isNext && this.openPage(mergeConfig) isNext && this.openPage(mergeConfig)
} else { } else {
this.openPage(mergeConfig) this.openPage(mergeConfig)
} }
} }
// 执行路由跳转 // 执行路由跳转
openPage(config) { openPage(config) {
// 解构参数 // 解构参数
const { const {
url, url,
type, type,
delta, delta,
animationType, animationType,
animationDuration animationDuration
} = config } = config
if (config.type == 'navigateTo' || config.type == 'to') { if (config.type == 'navigateTo' || config.type == 'to') {
uni.navigateTo({ uni.navigateTo({
url, url,
animationType, animationType,
animationDuration animationDuration
}) })
} }
if (config.type == 'redirectTo' || config.type == 'redirect') { if (config.type == 'redirectTo' || config.type == 'redirect') {
uni.redirectTo({ uni.redirectTo({
url url
}) })
} }
if (config.type == 'switchTab' || config.type == 'tab') { if (config.type == 'switchTab' || config.type == 'tab') {
uni.switchTab({ uni.switchTab({
url url
}) })
} }
if (config.type == 'reLaunch' || config.type == 'launch') { if (config.type == 'reLaunch' || config.type == 'launch') {
uni.reLaunch({ uni.reLaunch({
url url
}) })
} }
if (config.type == 'navigateBack' || config.type == 'back') { if (config.type == 'navigateBack' || config.type == 'back') {
uni.navigateBack({ uni.navigateBack({
delta delta
}) })
} }
} }
} }
export default (new Router()).route export default (new Router()).route
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论