项目中基本都会有个 公共的文件。 例如: utils.js 这里的结构是 export function ,所以采用 解构的方式直接带入使用更好。
export function formatNumber(n) { const str = n.toString() return str[1] ? str : `0${str}` } export function formatTime(date) { const year = date.getFullYear() const month = date.getMonth() + 1 const day = date.getDate() const hour = date.getHours() const minute = date.getMinutes() const second = date.getSeconds() const t1 = [year, month, day].map(formatNumber).join('/') const t2 = [hour, minute, second].map(formatNumber).join(':') return `${t1} ${t2}` } export function showToast(title) { wx.showToast({ title: title, icon: 'none' }) } export function debounce(func, delay) { let timer return function () { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { func.apply(this) }, delay) } } /** * * @param min 最小值 * @param max 最大值 * @returns {string} 带一位小数的随机数 */ export function getRandomDecimal(min, max) { return (min + (max - min) * Math.random()).toFixed(1) } /** * * @param min 最小值 * @param max 最大值 * @returns {Number} 整数随机数 */ export function getRandomNum(min, max) { return parseInt(min + (max - min) * Math.random()) } //将位置转换为地址 export function reverseGeocoder(qqmapsdk, {latitude, longitude}) { return new Promise((resolve, reject) => { qqmapsdk.reverseGeocoder({ location: { latitude: latitude, longitude: longitude, }, success: (res) => resolve(res), fail: (res) => reject(res) }) }) } /** * @param num 传入一个数 * @returns {boolean} 是小数返回true */ export function isDecimalNum(num) { return String(num).indexOf('.') !== -1 }使用:
import {reverseGeocoder,getRandomNum} from '../../utils/index' // 直接使用 reverseGeocoder(qqmapsdk, {latitude: result.lat, longitude: result.lng}).then(res => { this.saveStartPlace(res.result.address) this.saveFormattedStartPlace(res.result.formatted_addresses.recommend) })方式2: 采用对象的的方式
var exp = { // 节流函数, 保证一段时间内函数只执行一次 throttle(fn, delay) { var now, lastExec, timer, context, args var execute = function() { fn.apply(context, args) lastExec = now } return function() { context = this args = arguments now = Date.now() if (timer) { clearTimeout(timer) timer = null } if (lastExec) { var diff = delay - (now - lastExec) if (diff < 0) { execute() } else { timer = setTimeout(() => { execute() }, diff) } } else { execute() } } }, // 防抖函数,让某个函数在上一次执行后,满足等待某个时间内不再触发此函数后再执行,而在这个等待时间内再次触发此函数,等待时间会重新计算 debounce(func, wait, immediate) { var timeout, args, context, timestamp, result; var later = function() { var last = Date.now() - timestamp; if (last < wait && last >= 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); if (!timeout) context = args = null; } } }; return function() { context = this; args = arguments; timestamp = Date.now(); var callNow = immediate && !timeout; if (!timeout) timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; }, // 动画节流 rafThrottle(fn) { let locked,context,args return function() { if(locked) return context = this args = arguments locked = true aFrame(()=>{ locked = false fn.apply(context, args) }) } }, /* * 转换特殊字符*/ /*编码*/ encode:function(str) { var patt=/[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则 str = str.replace(patt, function(char){ var H, L, code; if (char.length===2) { H = char.charCodeAt(0); // 取出高位 L = char.charCodeAt(1); // 取出低位 code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法 return "&#" + code + ";"; } else { return char; } }); var entityMap = { "&": "&", "<": "<", ">": ">", '"': '\"', // "'": ''', "/": '/', "$":'$', ' ':' ' // "\\":"\\" }; // encodeURIComponent该方法是为了兼容后端不兼容\的问题 // return encodeURIComponent(String(str).replace(/[&<>"\/$]/g, function (s) { // return entityMap[s]; // })); var delStr = String(str).replace(/[&<>"\/\ $]/g, function (s) { return entityMap[s]; }); // return delStr.replace(/\n/g,'\\n').replace(/\\u00a0|\s+/ig, ''); }, } } export default exp使用点语法:
import util from "../../assets/js/util"; util.方法()