关于在vue项目中封装快捷工具的方法

31 篇文章 0 订阅
8 篇文章 2 订阅

话不多说,简单粗暴,直接上代码 !!!

首先根据项目开发规范在项目中新建tool.js文件,比如:我放在了项目中的src/utils/文件夹下
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import html2canvas from 'html2canvas';
import JsPDF from 'jspdf';

export default {
  // 获取日期跨度
  getDateSpan(action) {
    var star_time, end_time
    if (action == 'today') {
      star_time = this.getDateBefore(0) + ' 00:00:00'
      end_time = this.getDateBefore(0) + ' 23:59:59'
    }
    if (action == 'yesterday') {
      star_time = this.getDateBefore(1) + ' 00:00:00'
      end_time = this.getDateBefore(1) + ' 23:59:59'
    }
    if (action == 'lastweek') {
      star_time = this.getDateBefore(7) + ' 00:00:00'
      end_time = this.getDateBefore(0) + ' 23:59:59'
    }
    if (action == 'lastmonth') {
      star_time = this.getDateBefore(30) + ' 00:00:00'
      end_time = this.getDateBefore(0) + ' 23:59:59'
    }
    //console.log({star_time:star_time,end_time:end_time});
    return {
      star_time,
      end_time
    }
  },

  // 获取几天前的日期
  getDateBefore(n, step) {
    var uom = new Date(new Date() - n * 86400000)
    this.getFullYear = uom.getFullYear()
    this.getMonth = uom.getMonth() + 1
    this.getDate = uom.getDate()
    this.getHours = uom.getHours()
    this.getMinutes = uom.getMinutes()
    this.getSeconds = uom.getSeconds()
    this.getMonth = uom.getMonth() + 1 < 10 ? '0' + this.getMonth : this.getMonth
    this.getDate = uom.getDate() < 10 ? '0' + this.getDate : this.getDate
    this.getHours = uom.getHours() < 10 ? '0' + this.getHours : this.getHours
    this.getMinutes = uom.getMinutes() < 10 ? '0' + this.getMinutes : this.getMinutes
    this.getSeconds = uom.getSeconds() < 10 ? '0' + this.getSeconds : this.getSeconds
    if (step === '/') {
      uom = `${this.getFullYear}/${this.getMonth}/${this.getDate} ${this.getHours}:${this.getMinutes}:${this.getSeconds}`
    } else {
      uom = `${this.getFullYear}-${this.getMonth}-${this.getDate} ${this.getHours}:${this.getMinutes}:${this.getSeconds}`
    }

    return uom
  },

  // 获取当前时间
  getTodayEnd() {
    var date = new Date()
    var seperator1 = '-'
    var seperator2 = ':'
    var month = date.getMonth() + 1
    var strDate = date.getDate()
    if (month >= 1 && month <= 9) {
      month = '0' + month
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate
    }
    var currentdate = date.getFullYear() + '-' + month + '-' + strDate + ' 23:59:59'
    return currentdate
  },

  AddHours() {
    var date = new Date()
    var month = date.getMonth()
    var strDate = date.getDate()
    if (month >= 1 && month <= 9) {
      month = '0' + month
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate
    }
    var currentdate = date.getFullYear() + '-' + month + '-' + strDate + '00:00:00'

    return currentdate
  },

  // 获取当前时间
  getTodayBegin() {
    var date = new Date()
    var month = date.getMonth() + 1
    var strDate = date.getDate()
    if (month >= 1 && month <= 9) {
      month = '0' + month
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate
    }
    var currentdate = date.getFullYear() + '-' + month + '-' + strDate
    return currentdate
  },

  // 获取当天日期 带时分秒
  getTodayOnly() {
    var date = new Date()
    var month = date.getMonth() + 1
    var strDate = date.getDate()
    var hour = date.getHours() < 10 ? date.getHours() : date.getHours()
    var minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
    var second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
    if (month >= 1 && month <= 9) {
      month = '0' + month
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate
    }
    var currentdate = date.getFullYear() + '-' + month + '-' + strDate + ' ' + hour + ':' + minute + ':' + second
    return currentdate
  },

  /** 当前时间 时分秒,日期 相关参数配置如下:
   * 参数一:
   * @params 星期几 年月日 ==> 'W yyyy-MM-dd'
   * @params 星期几 年月日 时分秒 ==> 'W yyyy-MM-dd hh:mm:ss'
   * @params 年月日 ==> 'yyyy-MM-dd'
   * @params 年月日 时分秒 ==> 'yyyy-MM-dd hh:mm:ss'
   * @params 年月日 时分 ==> 'yyyy-MM-dd hh:mm'
   * @params 时分秒 ==> 'hh:mm:ss'
   * 参数二:
   * @params 年月日连接形式 ‘/’ 或 ‘-’(默认)
   */
  getDetailedDate(formatter, stape) {
    var date = new Date()
    this.year = date.getFullYear()
    this.month = date.getMonth() + 1
    //this.month = new Array('一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月')[this.month-1];
    this.date = date.getDate()
    this.hour = date.getHours()
    this.minute = date.getMinutes()
    this.second = date.getSeconds()
    this.week = new Array('星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六')[date.getDay()]
    this.month = date.getMonth() + 1 < 10 ? '0' + this.month : this.month
    this.date = date.getDate() < 10 ? '0' + this.date : this.date
    this.hour = date.getHours() < 10 ? '0' + this.hour : this.hour
    this.minute = date.getMinutes() < 10 ? '0' + this.minute : this.minute
    this.second = date.getSeconds() < 10 ? '0' + this.second : this.second

    var currentDate

    if (formatter === 'hh:mm:ss') {
      currentDate = `${this.hour}:${this.minute}:${this.second}`
    }
    if (formatter === 'yyyy') {
      currentDate = `${this.year}${stape === '/' ? stape : '-'}${this.month}${stape === '/' ? stape : '-'}${this.date}`
    }
    if (formatter === 'yyyy-MM') {
      currentDate = `${this.year}${stape === '/' ? stape : '-'}${this.month}${stape === '/' ? stape : '-'}${this.date}`
    }
    if (formatter === 'yyyy-MM-dd') {
      currentDate = `${this.year}${stape === '/' ? stape : '-'}${this.month}${stape === '/' ? stape : '-'}${this.date}`
    }
    if (formatter === 'W yyyy-MM-dd') {
      currentDate = `${this.week} ${this.year}${stape === '/' ? stape : '-'}${this.month}${stape === '/' ? stape : '-'}${this.date}`
    }
    if (formatter === 'yyyy-MM-dd hh:mm') {
      currentDate = `${this.year}${stape === '/' ? stape : '-'}${this.month}${stape === '/' ? stape : '-'}${this.date} ${this.hour}:${this.minute}`
    }
    if (formatter === 'yyyy-MM-dd hh:mm:ss') {
      currentDate = `${this.year}${stape === '/' ? stape : '-'}${this.month}${stape === '/' ? stape : '-'}${this.date} ${this.hour}:${this.minute}:${this.second}`
    }
    if (formatter === 'W yyyy-MM-dd hh:mm:ss') {
      currentDate = `${this.week} ${this.year}${stape === '/' ? stape : '-'}${this.month}${stape === '/' ? stape : '-'}${this.date} ${this.hour}:${this.minute}:${this.second}`
    }

    return currentDate
  },

  /** 根据时间戳转换时间
   *  @param timestamp: 时间戳
   *  @param format: 格式化形式
   *  @param shape: 年月日链接形式 (默认‘-’)
   */
  formatDate(timestamp, format, stape) {
    var date = new Date(parseInt(timestamp))
    this.year = date.getFullYear()
    this.month = date.getMonth() + 1
    this.date = date.getDate()
    this.hour = date.getHours()
    this.minute = date.getMinutes()
    this.second = date.getSeconds()
    this.month = date.getMonth() + 1 < 10 ? '0' + this.month : this.month
    this.date = date.getDate() < 10 ? '0' + this.date : this.date
    this.hour = date.getHours() < 10 ? '0' + this.hour : this.hour
    this.minute = date.getMinutes() < 10 ? '0' + this.minute : this.minute
    this.second = date.getSeconds() < 10 ? '0' + this.second : this.second

    var currentDate
    if (format === 'yyyy') {
      currentDate = `${this.year}`
    }
    if (format === 'hh:mm:ss') {
      currentDate = `${this.hour}:${this.minute}:${this.second}`
    }
    if (format === 'yyyy-MM') {
      currentDate = `${this.year}${stape === '/' ? stape : '-'}${this.month}`
    }
    if (format === 'yyyy-MM-dd') {
      currentDate = `${this.year}${stape === '/' ? stape : '-'}${this.month}${stape === '/' ? stape : '-'}${this.date}`
    }
    if (format === 'yyyy-MM-dd hh:mm') {
      currentDate = `${this.year}${stape === '/' ? stape : '-'}${this.month}${stape === '/' ? stape : '-'}${this.date} ${this.hour}:${this.minute}`
    }
    if (format === 'yyyy-MM-dd hh:mm:ss') {
      currentDate = `${this.year}${stape === '/' ? stape : '-'}${this.month}${stape === '/' ? stape : '-'}${this.date} ${this.hour}:${this.minute}:${this.second}`
    }

    return currentDate
  },

  /** 根据时间计算距今多久之前
   * @param date 传进来的时间
   */
  //时间转换
  getDiff(date) {
    var result
    var timespan = new Date(date).getTime()
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var month = day * 30;
    var now = new Date().getTime();
    var diffValue = now - timespan;
    if (diffValue < 0) { return result = "刚刚" }
    var monthC = diffValue / month;
    var weekC = diffValue / (7 * day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    var minC = diffValue / minute;
    if (monthC >= 1) {
      result = "" + parseInt(monthC) + "月前";
    }
    else if (weekC >= 1) {
      result = "" + parseInt(weekC) + "周前";
    }
    else if (dayC >= 1) {
      result = "" + parseInt(dayC) + "天前";
    }
    else if (hourC >= 1) {
      result = "" + parseInt(hourC) + "小时前";
    }
    else if (minC >= 1) {
      result = "" + parseInt(minC) + "分钟前";
    } else {
      result = "刚刚";
    }
    return result;
  },

  // 小数位取整 保留两位
  mathRound(x, num) {
    return Math.round(x * Math.pow(10, num)) / Math.pow(10, num)
  },

  // 过滤删除树形数据children分组为空的子项
  deleteEmptyGroup(treeData) {
    return new Promise(resolve => {
      function traversal(data) {
        data.map(item => {
          for (let info in item) {
            if (item['children']) {
              if (item['children'].length > 0) {
                traversal(item['children'])
              }
              if (item['children'].length == 0) {
                delete item['children']
              }
            }
          }
        })
      }
      traversal(treeData)
      resolve(treeData)
    })
  },

  // 数组去重
  unipue(arr) {
    if (!Array.isArray(arr)) return alert("type error");
    var newArray = [];
    for (var i = 0; i < arr.length; i++) {
      if (!newArray.includes(arr[i])) {
        newArray.push(arr[i]);
      }
    }
    return newArray;
  },

  // 多维数组扁平化
  arrayDelayer(arr) {
    if (!Array.isArray(arr)) return alert("type error");
    arr.flat(Infinity)
    return arr
  },

  // 表格导出 Excel 文件
  export(label, name) {
    // 生成 Excel 工作簿对象 raw: true 数字不采用科学计数法,默认为false
    var wb = XLSX.utils.table_to_book(label, { raw: true });
    // 获取二进制字符串作为输出
    var wbout = XLSX.write(wb, {
      bookType: 'xlsx',
      book: true,
      type: 'array',
    })
    try {
      FileSaver.saveAs(
        // Blob: 对象表示一个不可变 原始数据的类文件对象,不一定是JS原生格式的数据。
        // File: 基于Blob,继承了blob的功能并将其扩展使其支持用户系统上的文件。
        new Blob([wbout], { type: 'appliction/octet-stream' }),
        // 设置导出的文件名称可随意
        `${name}.xlsx`
      )
    } catch (e) {
      if (typeof console != 'undefined') console.log(e, wbout);
    }
    // 返回一个新创建的Blob对象,其内容由参数中给定的数组串联组成。
    return wbout
  },

  /**
   * @param  ele 要生成 pdf 的DOM元素(容器)
   * @param  padfName PDF文件生成后的文件名字
   */
  downloadPDF(ele, pdfName) {
    let eleW = ele.offsetWidth; // 获得该容器的宽
    let eleH = ele.offsetHeight; // 获得该容器的高
    let eleOffsetTop = ele.offsetTop;  // 获得该容器到文档顶部的距离
    let eleOffsetLeft = ele.offsetLeft; // 获得该容器到文档最左的距离
    var canvas = document.createElement("canvas");
    var abs = 0;
    let win_in = document.documentElement.clientWidth || document.body.clientWidth; // 获得当前可视窗口的宽度(不包含滚动条)
    let win_out = window.innerWidth; // 获得当前窗口的宽度(包含滚动条)
    if (win_out > win_in) {
      abs = (win_out - win_in) / 2; // 获得滚动条宽度的一半
    }
    canvas.width = eleW * 2; // 将画布宽高放大两倍
    canvas.height = eleH * 2;
    var context = canvas.getContext("2d");
    context.scale(2, 2);
    context.translate(-eleOffsetLeft - abs, -eleOffsetTop);
    // 这里默认横向没有滚动条的情况,因为offset.left(),有无滚动条的时候存在差值,因此
    // translate的时候,要把这个差值去掉
    // html2canvas(element).then( (canvas)=>{ //报错
    // html2canvas(element[0]).then( (canvas)=>{
    html2canvas(ele, {
      dpi: 300,
      // allowTaint: true, //允许 canvas 污染, allowTaint参数要去掉,否则是无法通过toDataURL导出canvas数据的
      useCORS: true  // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
    }).then((canvas) => {
      var contentWidth = canvas.width;
      var contentHeight = canvas.height;
      // 一页pdf显示html页面生成的canvas高度;
      var pageHeight = contentWidth / 592.28 * 841.89;
      // 未生成pdf的html页面高度
      var leftHeight = contentHeight;
      // 页面偏移
      var position = 0;
      // a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
      var imgWidth = 595.28;
      var imgHeight = 595.28 / contentWidth * contentHeight;
      var pageData = canvas.toDataURL('image/jpeg', 1.0);
      var pdf = new JsPDF('', 'pt', 'a4');
      // 有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
      // 当内容未超过pdf一页显示的范围,无需分页
      if (leftHeight < pageHeight) {
        // 在pdf.addImage(pageData, 'JPEG', 左,上,宽度,高度)设置在pdf中显示;
        pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
        // pdf.addImage(pageData, 'JPEG', 20, 40, imgWidth, imgHeight);
      } else { // 分页
        while (leftHeight > 0) {
          pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
          leftHeight -= pageHeight;
          position -= 841.89;
          // 避免添加空白页
          if (leftHeight > 0) {
            pdf.addPage();
          }
        }
      }
      //可动态生成
      pdf.save(pdfName);
    })
  },

  // 验证手机号
  isMobile(s) {
    return /^1[0-9]{10}$/.test(s)
  },

  // 截取url获取参数
  getQueryVariable(sUrl, sKey) {
    sUrl = sUrl.toString();
    let allUrl = sUrl.split("?")[1].split("#")[0];
    if (sKey) { // 指定参数名
      var strs = allUrl.split("&")
      var paramsArr = new Array()
      for (var i = 0, len = strs.length; i < len; i++) {
        var temp = strs[i].split("=")
        if (temp[0] === sKey) {
          paramsArr.push(temp[1])
        }
      }
      if (paramsArr.length === 0) {  // 找不到指定参数
        return ""
      }
      if (paramsArr.length === 1) { //只匹配到一个唯一key
        return paramsArr[0]
      } else { // 多个同名参数key
        return paramsArr
      }
    } else { // 不指定参数名
      if (allUrl === undefined || allUrl === "") { // 路径无参
        return {}
      }
      var strs = allUrl.split("&")
      var objArr = new Object()
      for (var i = 0, len = strs.length; i < len; i++) { // 遍历所有参数值
        var temp = strs[i].split("=")
        if (!(temp[0] in objArr)) {
          objArr[temp[0]] = []
        }
        objArr[temp[0]].push(temp[1])
      }
      return objArr
    }
  },
}


在需要的页面中怎么使用,我们以格式化时间为例,请往下看:
1. 首先在需要的页面中引入
import timeFomatter from '@/utils/tools'
2. 在data函数中定义一个变量,比如: currentTime当前时间
export default {
	data() {
		return {
			currentTime: '',
		}
	}
}
3. 在created生命周期函数中书写调用相关函数的方法
created() {
	//在页面创建加载的时候调用该函数
	this.getTime()
}
methods: {
	getTime(){
		/** 获取当前时间 相关参数配置如下:
       * @params 星期几 年月日 ==> 'W yyyy-MM-dd'
       * @params 星期几 年月日 时分秒 ==> 'W yyyy-MM-dd hh:mm:ss'
       * @params 年月日 ==> 'yyyy-MM-dd'
       * @params 年月日 时分秒 ==> 'yyyy-MM-dd hh:mm:ss'
       * @params 年月日 时分 ==> 'yyyy-MM-dd hh:mm'
       * @params 时分秒 ==> 'mm:hh:ss'
       * 或参看封装好的时间格式化工具, 不满足的可以自行根据需求更改优化: 'src/utils/tools.js'
       */
		const _this = this
		setInterval(() => {
			_this.currentTime = timeFomatter.getDetailedDate('yyyy-MM-dd hh:mm:ss')
		}, 1000)
	}
}
4.最后在页面中使用
<div class="header-time">{{ currentTime }}</div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值