vue插件的开发

之前项目中使用到一些公共的处理函数。一直的做法是写在一个JS文件中,用的时候在引用此文件。
这样就是每个组件都要引用,在页面模板处理数据时,如格式化日期等还需要将对应的函数赋值给过滤器来使用。
最近改成了写成vue插件的形式,方便许多。
1、新建一个JS文件。
2、如下示例代码

const Plugin = {};
Plugin.install = (Vue, options) => {
  /*
 * 格式化日期 
 * type 01 '-' 02 '/' 03  '.'
 * format  01 年月日  02 年月日 时分 03 年月日时分秒
 * */
  Vue.prototype.$formatDate = (date, type, format) => {
    if (!date) {
      return ""
    } else {
      let nowDate = new Date(date);
      let y = nowDate.getFullYear();
      let m = nowDate.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      let d = nowDate.getDate();
      d = d < 10 ? "0" + d : d;
      let h = nowDate.getHours();
      h = h < 10 ? "0" + h : h;
      let min = nowDate.getMinutes();
      min = min < 10 ? "0" + min : min;
      let s = nowDate.getSeconds();
      s = s < 10 ? "0" + s : s;
      let separatorType = "";
      switch (type) {
        case '01':
          separatorType = '-';
          break;
        case '02':
          separatorType = '/';
          break;
        case '03':
          separatorType = '.';
          break;
        default:
          separatorType = '-';
          break;
      }
      if (format == '01') { //年月日
        return y + separatorType + m + separatorType + d;
      } else if (format == '02') { //年月日 时分
        return y + separatorType + m + separatorType + d + " " + h + ":" + min;
      } else if (format == '03') { //年月日  时分秒
        return y + separatorType + m + separatorType + d + " " + h + ":" + min + ":" + s;
      } else {
        alert('时间格式输入有误')
      }
    }
  }

 
  /**
   * 比较两个时间大小
   * 第一个参数大返回true,否则返回false
   * */
  Vue.prototype.$compareDate = (date1, date2) => {
    let oDate1 = new Date(date1);
    let oDate2 = new Date(date2);
    if (oDate1.getTime() >= oDate2.getTime()) {
      return true;
    } else {
      return false;
    }
  };


}

export default Plugin;

3、在main.js中引入。

import Plugin from "你的文件路径"

Vue.use(Plugin) //使用插件

4、组件中使用。

//JS中使用
this.$compareDate(this.beginTime, this.endTime)
//template中使用
{date || $formatDate ('01','01')}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值