以下是个人过去一年在vue项目的开发过程中经常会用到的一些公共方法,在此进行汇总,方便以后及有需要的朋友查看~
let util = {};
/** * @description 日期格式化 * @param {Date} date 日期 * @param {String} fmt 日期格式 eg: yyyy-MM-dd hh:mm:ss */ util.dateFormat = function (date, fmt) { var 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(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)); } for (var k in o) { if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))); } } return fmt; };
/** * @description 文件下载 * @param {Object} data 数据 * @param {String} fileName 下载文件名 */ util.download = function (data, fileName) { //创建一个blob对象,file的一种 let blob = new Blob([data], { type: 'application/x-xls' }); if ('download' in document.createElement('a')) { // 非IE下载 let link = document.createElement('a'); if (window.URL) { link.href = window.URL.createObjectURL(blob); } else { link.href = window.webkitURL.createObjectURL(blob); } link.download = fileName; document.body.appendChild(link); link.click(); link.remove(); }else { // IE10+下载 navigator.msSaveBlob(blob, fileName); } };
/** * @description 校验导入execl格式 * @param {file} file 导入文件对象 */ util.validateExecl = function(file) { const isXLS = file.type === 'application/vnd.ms-excel'; const isXLSX = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; if (!isXLS && !isXLSX) { this.$message.error('只支持导入execl文件'); return false; } };
/** * @description 校验上传图片格式和大小 * @param {file} file 导入文件对象 */ util.validateImage = function(file) { const isPNG = file.type.toLowerCase() === 'image/png'; const isJPG = file.type.toLowerCase() === 'image/jpeg'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG && !isPNG) { this.$message.error('上传图片只能是JPG或PNG格式!'); return false; } if (!isLt2M) { this.$message.error('上传图片大小不能超过 2M!'); return false; } };
export default util;
持续更新中~~