1.概念:
此文件狭存放自己封装的工具类函数,是一个共享的方法。
2.使用:
import conf from '../config'; export const $ = {}; /** * * @param time * @returns {number} */ export const unify = function (time) { time -= 0; if (('' + time).length === 10) { time *= 1000; } return time; }; export const formatDiffTime = function (time) { let ago, curTime, diff, int; time = unify(time); int = parseInt; curTime = +new Date(); diff = curTime - time; ago = ''; if (1000 * 60 > diff) { ago = '刚刚'; } else if (1000 * 60 <= diff && 1000 * 60 * 60 > diff) { ago = int(diff / (1000 * 60)) + '分钟前'; } else if (1000 * 60 * 60 <= diff && 1000 * 60 * 60 * 24 > diff) { ago = int(diff / (1000 * 60 * 60)) + '小时前'; } else if (1000 * 60 * 60 * 24 <= diff && 1000 * 60 * 60 * 24 * 30 > diff) { ago = int(diff / (1000 * 60 * 60 * 24)) + '天前'; } else if (1000 * 60 * 60 * 24 * 30 <= diff && 1000 * 60 * 60 * 24 * 30 * 12 > diff) { ago = int(diff / (1000 * 60 * 60 * 24 * 30)) + '月前'; } else { ago = int(diff / (1000 * 60 * 60 * 24 * 30 * 12)) + '年前'; } return ago; } export const timeFormat = (time, format = 'yyyy-MM-dd hh:mm:ss') => { const time_type = typeof time; const date = time_type === 'object' ? time : time_type === 'number' ? new Date(time) : new Date(); const o = { 'M+': date.getMonth() + 1, //月份 'd+': date.getDate(), //日 'h+': date.getHours(), //小时 'm+': date.getMinutes(), //分 's+': date.getSeconds(), //秒 'q+': Math.floor((date.getMonth() + 3) / 3), //季度 'S' : date.getMilliseconds(), //毫秒 }; if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)); for (let k in o) if (new RegExp('(' + k + ')').test(format)) format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))); return format; }; /** * 调试信息 * @param msg */ export const log = (msg) => { if (process.env.NODE_ENV !== 'production') { console.log(msg) } }; /** * 本地localStore存储 * @param key * @param value * @returns {*} */ export const localStore = (key, value) => { if (!key) return false; return value ? (localStorage.setItem(key, JSON.stringify(value))) : JSON.parse(localStorage.getItem(key)); }; /** * 本地sessionStore存储 * @param key * @param value * @returns {*} */ export const sessionStore = (key, value) => { if (!key) return false; return value ? (sessionStorage.setItem(key, JSON.stringify(value))) : JSON.parse(sessionStorage.getItem(key)); }; /** * 文件上传 * @param files * @param host * @param param * @param options */ $.uploadFile = (files, host, param, options) => { // 添加图片数据 const formdata = new FormData(); Object.keys(param).forEach(key => { formdata.append(key, param[key]) }); files.forEach(file => { formdata.append('file', file) }); // 定义 xhr const xhr = new XMLHttpRequest(); xhr.open('POST', host); // 设置超时 xhr.ontimeout = (res) => { options.error && options.error(res); }; // 返回数据 xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200) { options.success && options.success('upload success'); } else { options.error && options.error('upload error'); } } }; // 发送请求 xhr.send(formdata) }; /** * 获取上传签名 * @returns {Promise<*>} */ export const upload_sign = async () => { let res = await ax.post('/oss'); console.log(res); if (res.status === 200) { return res.data; } } export const PrefixInteger = (num, n) => { return (Array(n).join(0) + num).slice(-n); } export const upload_img = (para, name, dirname, count, callback) => { let uploadCount = 0; weui.uploader('#' + name, { url : conf.oss.dev, compress: { width : 1600, height : 1600, quality: .85, }, onBeforeQueued(files) { // `this` 是轮询到的文件, `files` 是所有文件 if (['image/jpg', 'image/jpeg', 'image/png', 'image/gif'].indexOf(this.type) < 0) { weui.alert('请上传图片'); return false; // 阻止文件添加 } if (this.size > 10 * 1024 * 1024) { weui.alert('请上传不超过10M的图片'); return false; } if (files.length > count) { weui.alert('最多只能上传' + count + '张图片,请重新选择'); return false; } //if (uploadCount >= count) { // weui.alert('一次最多只能上传'+count+'张图片'); // return false; //} //++uploadCount; //return true; // 阻止默认行为,不插入预览图的框架PrefixInteger }, onBeforeSend(data, headers) { weui.loading('上传中...'); data.success_action_status = 200; data.OSSAccessKeyId = para['accessid']; data.signature = para['signature']; data.policy = para['policy']; data.key = para['dir']+dirname + para['imageIdPrefix'] + PrefixInteger(this.id, 4) + '.jpg'; }, onError : async function (err) { if (this.xhr && this.xhr.status === 200) { let img = para['dir'] + dirname + para['imageIdPrefix'] + PrefixInteger(this.id, 4) + '.jpg'; callback(img, para['imageIdPrefix'] + PrefixInteger(this.id, 4)); weui.loading().hide(); return true;// 阻止默认行为,不使用默认的失败态 } else { weui.loading().hide(); weui.alert('上传失败,请重新选择上传哦~'); } }, }); } // 遍历对象 export const objForEach = (obj, fn) => { let key, result; for (key in obj) { if (obj.hasOwnProperty(key)) { result = fn.call(obj, key, obj[key]); if (result === false) { break } } } }; // 遍历类数组 export const arrForEach = (fakeArr, fn) => { let i, item, result; const length = fakeArr.length || 0; for (i = 0; i < length; i++) { item = fakeArr[i]; result = fn.call(fakeArr, item, i); if (result === false) { break } } }; //深拷贝 export const deepCopy = (obj) => { if (typeof obj != 'object') { return obj; } let newobj = {}; for (let attr in obj) { newobj[attr] = deepCopy(obj[attr]); } return newobj; } // 时间选择 export const select_hours = () => { let hours = []; for (let i = 0; i < 24; i++) { let hours_item = {}; hours_item.label = ('' + i).length === 1 ? '0' + i : '' + i; hours_item.value = i; hours.push(hours_item); } return hours; } export const select_minites = () => { let minites = [] for (let j = 0; j < 60; j++) { let minites_item = {}; minites_item.label = ('' + j).length === 1 ? '0' + j : '' + j; minites_item.value = j; minites_item.disabled = true; minites.push(minites_item); } return minites } export const select_time = (name, fn) => { let t = '' let myDate = new Date(); let year=myDate.getFullYear(); let month=myDate.getMonth(); let day=myDate.getDate(); weui.datePicker({ start :2018, end : 2050, defaultValue: [year, month, day], onChange : function (result) { }, onConfirm : function (result) { arrForEach(result, (res, i) => { if (i === 2) { t = t + res.value } else { t = t + res.value + '-' } }) fn(t); }, id : name, }); }; export const select_detail_time = (name, fn) => { let t = '' let hours = select_hours(); let myDate = new Date(); let hour=myDate.getHours(); weui.picker(hours, { defaultValue: [hour], onChange : function (result) { }, onConfirm : function (result) { arrForEach(result, (res, i) => { if (i === 1) { t = t + '00' } else { t = ' ' + t + res.label } }) fn(t); }, id : 'datePicker4', }); } //let hours = [], // minites = [], // symbol = [{ label: ':', value: 0 }]; //function show_expect_time_picker(_this, date) { // var date = date[0].label + date[1].label + date[2].label; // if (!hours.length) { // for (var i = 0; i< 24; i++) { // var hours_item = {}; // hours_item.label = ('' + i).length === 1 ? '0' + i : '' + i; // hours_item.value = i; // hours.push(hours_item); // } // } // if (!minites.length) { // for (var j= 0; j < 60; j++) { // var minites_item = {}; // minites_item.label = ('' + j).length === 1 ? '0' + j : '' + j; // minites_item.value = j; // minites.push(minites_item); // } // } // // weui.picker(hours, symbol, minites, { // defaultValue: [new Date().getHours()+1, 0, 0], // onConfirm: function(result) { // var time = result[0].label + ':' + result[2].label; // var expect_date = date + ' ' + time; // $(_this).find('.weui-cell__ft').text(expect_date); // }, // id: 'ma_expect_time' // }); //} /** * 验证身份证号是否合法 * @param identity * @returns {boolean} */ export const checkIdentity = (identity) => { let reg = /^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16}([0-9]|[xX])$/; return reg.test(identity); } /** * 验证手机号是否合法 * @param str * @returns {boolean} */ export const isPoneAvailable = (str) => { let myreg = /^[1][3,4,5,7,8][0-9]{9}$/; return myreg.test(str) } /** *验证姓名是否是中文 * @param str * @returns {boolean} */ export const checkStr = (str) => { // [\u4E00-\uFA29]|[\uE7C7-\uE7F3]汉字编码范围 let reg = /^[\u4E00-\u9FA5]+$/; return reg.test(str) } export const monoObject = (obj) => { if (typeof obj !== 'object') { return obj; } let newObj = {}; for (let key in obj) { newObj[key] = $.monoObject(obj[key]); } return newObj; }; export const setTitle = (title) => { document.title = title; }; export const scrolltobottom = (callback, offset) => { if (!callback) { window.off('scroll'); return; } offset = offset || 44; window.on('scroll', function () { if (document.scrollTop() + offset >= document.height() - window.height()) callback(); }); }; export const oss = conf.oss.dev