Vue2常用功能日常总结(2) - 常用方法集合
常用功能方法集合及默认导出
/** * @description:本文件为一些常用的工具函数以及一些JS功能代码集合 */
window.downloadFile = function (sUrl) { // iOS devices do not support downloading. We have to inform user about this. if (/(iP)/g.test(navigator.userAgent)) { alert('Your device does not support files downloading. Please try again in desktop browser.') return false } // If in Chrome or Safari - download via virtual link click if (window.downloadFile.isChrome || window.downloadFile.isSafari) { // Creating new link node. var link = document.createElement('a') link.href = sUrl if (link.download !== undefined) { // Set HTML5 download attribute. This will prevent file from opening if supported. var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length) link.download = fileName } // Dispatching click event. if (document.createEvent) { var e = document.createEvent('MouseEvents') e.initEvent('click', true, true) link.dispatchEvent(e) return true } } // Force file download (whether supported by server). if (sUrl.indexOf('?') === -1) { sUrl += '?download' } window.open(sUrl, '_self') return true } window.downloadFile.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1 window.downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1 /** * @name: downloadFile * @description:文件下载:利用浏览器自带下载功能,进行文件下载(浏览器不弹出新窗口) * @param {String} sUrl: 文件链接地址 * @returns {Boolean} */ const downloadFile = window.downloadFile /** * @name: downloadFileWithFlow * @description:流数据生成文件下载 * @param {Null} flow: 文件流数据 * @param {String} fileTit: 生成文件的名称 */ const downloadFileWithFlow = function (flow, fileTit) { let elink = document.createElement('a') elink.download = fileTit + '.xlsx' elink.style.display = 'none' let blob = new Blob([flow], { type: 'application/vnd.ms-excel;charset=utf-8' }) elink.href = URL.createObjectURL(blob) document.body.appendChild(elink) elink.click() document.body.removeChild(elink) } /** * @name: handleObjProperty * @description:对象属性封装处理 * @param {Array} propertyList: 需要封装处理的属性列表 * @param {Object} obj: 原对象 * @param {Object} container: 属性容器 * @returns {Object} 属性封装完成后的容器对象 */ const handleObjProperty = function (propertyList, obj, container = {}) { return propertyList.reduce((iter, val) => { if (val in obj && obj[val]) { container[val] = obj[val] } else { container[val] = '' } return container }, container) } /** * @name: btnLoading * @description: 设置操作按钮Loading * @returns {Boolean} */ const btnLoading = function () { setTimeout(() => { return false }, 300) return true } /** * @name: setDocumentTitle * @description:设置项目浏览器图标和标题 * @param {Object} configData: 图标、标题、其他信息等配置 数据对象 * @param {String} favicon: 图标属性字段 * @param {String} title: 标题属性字段 * @param {String} other: 其他属性字段 */ const setDocumentTitle = function (configData, favicon, title, other) { var link = document.querySelector("link[rel*='icon']") || document.createElement('link') link.type = 'image/x-icon' link.rel = 'shortcut icon' link.href = configData[favicon] ? configData[favicon] : '' document.getElementsByTagName('head')[0].appendChild(link) document.title = other ? (configData[title] ? configData[title] : '') + (configData[other] ? configData[other] : '') : configData[title] ? configData[title] : '' } /** * 时间值格式化(时:分:秒) */ const setTimeFormatHHmmSS = function (startTime, currentTime) { let dateDiff = startTime - currentTime // 时间差的总毫秒数 let hh = Math.floor(dateDiff / (3600 * 1000)) // 计算出相差小时数 let mmDiff = dateDiff % (3600 * 1000) // 计算小时数后剩余的毫秒数 let mm = Math.floor(mmDiff / (60 * 1000)) // 计算出相差分钟数 let ssDiff = mmDiff % (60 * 1000) // 计算分钟数后剩余的毫秒数 let ss = Math.round(ssDiff / 1000) // 计算出相差秒数 return `${hh < 10 ? '0' + hh : hh}:${mm < 10 ? '0' + mm : mm}:${ss < 10 ? '0' + ss : ss}` } /** * 清除路由历史记录,防止页面后退 */ const preventPageBack = function () { // 防止页面后退 history.pushState(null, null, document.URL) window.addEventListener('popstate', function () { history.pushState(null, null, document.URL) }) } /** * 生成随机字符串(生成随机id) * @param {*} length: 需要生成的字符串长度,非必传,默认生成8位 * @param {*} chars: 字符串指定字符,非必传 * @description:使用场景:1、用于前端生成随机的ID,现在不管是Vue还是React都需要绑定key * 2、在进行http请求时,避免浏览器因请求相同而不发送请求,也经常需要在请求链接上添加一些随机字符串,以作区分(更多的时候是后缀时间戳) */ const getUUID = function (length, chars) { length = length || 8 chars = chars || '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' let result = '' for (let i = length; i > 0; --i) { result += chars[Math.floor(Math.random() * chars.length)] } return result } /** * 对象转化为FormData对象 * @param {Object} object * @description:使用场景:上传文件时需要构建一个FormData对象,然后有多少个参数就append多少次,该函数可以简化逻辑 */ const getFormData = function (object) { let formData = new FormData() Object.keys(object).forEach(key => { const value = object[key] if (Array.isArray(value)) { value.forEach((subValue, i) => formData.append(key + `[${i}]`, subValue)) } else { formData.append(key, object[key]) } }) return formData } export default { /** * 文件下载 */ downloadFile: downloadFile, /** * 文件下载(通过A标签) */ downloadFileWithFlow: downloadFileWithFlow, /** * 对象属性封装处理 */ handleObjProperty: handleObjProperty, /** * 设置操作按钮Loading */ btnLoading: btnLoading, /** * 设置项目浏览器图标和标题 */ setDocumentTitle: setDocumentTitle, /** * 将两个时间戳差值格式化成(时:分:秒)格式 */ formatTimeHHmmSS: setTimeFormatHHmmSS, /** * 清除路由历史记录,防止页面后退 */ preventPageBack: preventPageBack, /** * 生成随机字符串 */ getUUID: getUUID, /** * 对象转化为FormData对象 */ getFormData: getFormData }