之前项目中使用到一些公共的处理函数。一直的做法是写在一个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')}