开发项目中可以总结一些公共的js代码来方便开发,用到的时候就可以直接复制使用
下面提供几个方法,绑定到了Vue的原型对象上,也可以建立单独的js文件import到项目中
1、获取当天日期或当天时间
// 获取当天年月日,参数showTime:是否显示时分秒; Vue.prototype.$currentDate = function (showTime) { function zeroFilling(n){ if(n<10) n = '0' + n return n } let [cDate,year,month,date,h,m,s,currentDate] = [new Date(),'','','','','','',''] year = cDa() month = cDa() + 1; date = cDa(); h = cDa(); m = cDa(); s = cDa(); month = zeroFilling(month) date = zeroFilling(date) h = zeroFilling(h) m = zeroFilling(m) s = zeroFilling(s) if(showTime){ currentDate = `${year}-${month}-${date} ${h}:${m}:${s}`; }else{ currentDate = `${year}-${month}-${date}`; } return currentDate; } // 使用方法 this.$currentDate() this.$currentDate(true)
2、时间格式化
针对后台返回的例如202001、20200118数据
由前端转换成"yyyy-MM-dd"和"yyyy-MM-dd 至 yyyy-MM-dd"格式的方法
/* 格式化时间格式 参数timeData:时间(字符串/数组对象); 参数type:年月日分隔符; 参数text:开始结束时间分隔符; */ Vue.prototype.$formatTime = function (timeData,type,text) { function str(timeData,type){ i == 6){ return (0,4) + type + (4,6) }else i == 8){ return (0,4) + type + (4,6) + type + (6,8) } } function obj(timeData,type,text){ let [time1,time2] = ['',''] if(timeData[0].length == 6 || timeData[0].length == 8){ time1 = str(timeData[0],type) } if(timeData[1].length == 6 || timeData[1].length == 8){ time2 = str(timeData[1],type) } return time1 + text + time2 } if(typeof timeData == 'string'){ return str(timeData,type) }else if(typeof timeData == 'object'){ return obj(timeData,type,text) } } // 使用方法 this.$formatTime('202001','-') => 2020-01 this.$formatTime('20200118','-') => 2020-01-18 this.$formatTime(['20200101','20200118'],'-',' 至 ') => 2020-01-01 至 2020-01-18 this.$formatTime(['2020-01-01','2020-01-18'],'-',' 至 ') => 2020-01-01 至 2020-01-18
3、获取地址栏参数
// 获取地址栏参数,参数name:地址栏参数名; Vue.prototype.$getParam = function (name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var r = window.loca(1).match(reg); if (r != null) { return unescape(r[2]); } else { return null; } }; // 使用方法 // localhost:8080/articleDetail?id=123 this.$getParam('id') => '123'
注:以上方法可进一步化简