记录一些项目中常用的公共方法

// 格式化时间
function parseTime(time, cFormat) {
	if (arguments.length === 0) {
		return null
	}
	const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if (typeof time === 'string' && isIos()) {
			time = time.replace(/\-/g, '/')
		}
		if (('' + time).length === 10) time = parseInt(time) * 1000
		date = new Date(time)
	}
	if (date.getTime() === 0) {
		return '-'
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value]
		}
		if (result.length > 0 && value < 10 && key === 'd') {
			value = '0' + value
		}
		return value.toString().padStart(2, '0')
	})
	return time_str
}
// 使用  

parseTime(new Date().getTime(), '{y}-{m}-{d}') // 结果 2020-05-10

 

//防抖 延迟执行
const debounce = (fn, delay = 500) => {
	let timer
	return function() {
		let args = arguments
		if (timer) clearTimeout(timer)
		timer = setTimeout(() => {
			timer = null
			fn.apply(this, args)
		}, delay)
	}
}

//节流 每delay毫秒仅执行一次fn
const throttle = (fn, delay = 1000) => {
	let last = 0
	return function() {
		let now = new Date()
		if (now - last > delay) {
			fn.apply(this, arguments)
			last = now
		}
	}
}

  

// uni-app使用html5+创建一个确认弹框  

const confirm = (opt = {}) => { let pageWidth = uni.getSystemInfoSync().screenWidth; // 屏幕宽度 let pageHeight = uni.getSystemInfoSync().screenHeight; // 屏幕高度 let contentWidth = pageWidth * 0.7; // 弹窗宽度 let contentHeight = opt.height || 180; // 弹窗高度 let btnHeight = 50; // 按钮高度 let title = opt.title || '提示'; let content = opt.content || '确定继续当前操作吗?'; let cancelBtnText = opt.cancelBtnText || '取消'; let confirmBtnText = opt.confirmBtnText || '确定'; // 创建蒙版层 let maskView = new plus.nativeObj.View('maskView'); maskView.drawRect({color: "rgba(2, 15, 10, .3)"}); // 创建内容区域 let contentView = new plus.nativeObj.View('contentView',{ top:`${(pageHeight - contentHeight) / 2}px`, left:`${(pageWidth - contentWidth) / 2}px`, width:`${contentWidth}px`, height:`${contentHeight}px`, }); let tagList = []; // 所有节点集合 // 填充颜色,设置圆角 tagList.push({ id: 'xgContent', tag: 'rect', rectStyles: {color: "#fff",radius: '10px'} }) // 创建弹窗标题 tagList.push({ id: 'xgTitle', tag: 'font', text: title, position: {top:'10px',left:'10px',width:'100%',height:'20px'}, // 控件区域位置的起点和宽高 textStyles: {align:'left',size:'16px',color:'#333'}, // 文本样式 }) // 创建显示的文本内容 tagList.push({ id: 'xgContentBody', tag: 'font', text: content, position: {top: '30px',left: '10px',width: `${contentWidth - 20}px`,height:`${(contentHeight - btnHeight - 40)}px`}, textStyles: {align:'center',size:'16px',color:'#333',whiteSpace: "normal",overflow:'ellipsis'}, }) // 创建按钮,弹窗左下的按钮 let cancelBtnPosition = {bottom:'0',left:'0',width:'50%',height:`${btnHeight}px`}; tagList.push({ id: 'xgCancel', tag: 'rect', rectStyles: {radius: '10px'}, position: cancelBtnPosition, }) tagList.push({ id: 'xgCancelBtnText', tag: 'font', text: cancelBtnText, position: cancelBtnPosition, textStyles: {align:'center',size:'16px',color:'#aaa'}, }) // 弹窗右下的按钮 let confirmBtnPosition = {bottom:'0',left:'50%',width:'50%',height:`${btnHeight}px`}; tagList.push({ id: 'xgConfirm', tag: 'rect', rectStyles: {radius: '10px'}, position: confirmBtnPosition, }) tagList.push({ id: 'xgConfirmBtnText', tag: 'font', text: confirmBtnText, position: confirmBtnPosition, textStyles: {align:'center',size:'16px',color:'#ffa515'}, }) // 弹窗上面和中间的线条 // contentView.drawRect({color: "#ddd"}, {bottom:'0',left:'50%',width:'1px',height:`${btnHeight}px`}); // contentView.drawRect({color: "#ddd"}, {bottom:`${btnHeight}px`,left:'0',width:'100%',height:'1px'}); tagList.push({ tag: 'rect', color: "#ddd", position: {bottom:`${btnHeight}px`,left:'0',width:'100%',height:'1px'}, }) tagList.push({ tag: 'rect', color: "#ddd", position: {bottom:'0',left:'50%',width:'1px',height:`${btnHeight}px`}, }) contentView.draw(tagList) // 确定或取消的按钮事件 contentView.addEventListener('click',(e)=>{ // 需要计算点击的位置来判断是确定还是取消事件 if(e.clientY > contentHeight - btnHeight){ if(e.clientX < contentWidth / 2){ // 取消事件 if(opt.cancel && typeof opt.cancel === 'function') opt.cancel() }else{ // 确定事件 if(opt.confirm && typeof opt.confirm === 'function') opt.confirm() } // 不管是确定还是取消,都关闭弹窗 maskView.hide(); contentView.hide(); } }) maskView.addEventListener('click',(e)=>{ if(opt.maskClose){ maskView.hide(); contentView.hide(); } }) maskView.show(); contentView.show(); }

  

// 深度克隆
function deepClone (obj) {
	// 对常见的“非”值,直接返回原来值
	if([null, undefined, NaN, false].includes(obj)) return obj;
    if(typeof obj !== "object" && typeof obj !== 'function') {
		//原始类型直接返回
        return obj;
    }
    var o = isArray(obj) ? [] : {};
    for(let i in obj) {
        if(obj.hasOwnProperty(i)){
            o[i] = typeof obj[i] === "object" ? deepClone(obj[i]) : obj[i];
        }
    }
    return o;
}

  

//json参数转url参数
export const jsonToQuery = (param) => {
	if(!param || typeof param!=='object' || Object.keys(param).length==0){
		return ''
	}
	let arr = []
	let keys = Object.keys(param)
	for(let i of keys){
		let t = i+'='+param[i]
		arr.push(t)
	}
	return arr.join('&')
}
//url参数转json参数
export const urlToJson = (url) => {
	let path = url
	let param = {}
	if (url.indexOf('?') != -1) {
		path = url.substr(0, url.indexOf('?'))
		let arr = url.split("?")[1].split("&")  
		arr.forEach(i=>{
			if (i.split("=")[1] && i.split("=")[1] != 'undefined') param[i.split("=")[0]] = i.split("=")[1]
		})
	} 
	return { path, param }
}
//url获取指定参数
export const getQuery = (key) => {
	 let query = window.location.search.substring(1);
	 let vars = query.split("&");
	 for (let i=0;i<vars.length;i++) {
		let pair = vars[i].split("=");
		if (pair[0] == key) {return pair[1];}
	 }
	 return(false)
}

  先这样,后面有补充再加

 

posted @ 2020-11-19 09:51  飞天狼  阅读(132)  评论(0编辑  收藏  举报