基于elementui的年月日周时间控件

2021/4/27 18:59:29

本文主要是介绍基于elementui的年月日周时间控件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

组件
<template>
	<div class="component_search_form_date clearfix">
		<el-radio-group v-model="curType" :size="moduleSize" style="float: left;" @change="radioChange">
			<el-radio-button v-for="item in showBtnList" :key="item.value" :label="item.value">{{ item.name }}</el-radio-button>
		</el-radio-group>
		&emsp;
		<div style="display: inline-block; float: left; margin-left: 5px;">
			<template v-if="dateType == 'daterange'">
				<!-- 日期 范围选择 -->
				<el-date-picker
					key="daterange"
					v-model="dataForm.rangeDate"
					type="daterange"
					value-format="yyyy-MM-dd HH:mm:ss"
					:picker-options="{ disabledDate: time => !(time.getTime() >= Date.now() - 31 * 8.64e7 && time.getTime() < Date.now() - 8.64e7) }"
					start-placeholder="开始日期"
					end-placeholder="结束日期"
					style="width: 240px;"
					@change="datePickerChage"
					:size="moduleSize"
				/>
			</template>
			<template v-else-if="dateType == 'weekrange'">
				<!-- 周 范围选择 -->
				<!-- <el-date-picker
					key="weekrange1"
					v-model="dataForm.dateStart"
					type="week"
					:picker-options="{ disabledDate: time => datePickerDisable(time, dataForm.dateEnd, '>='), 'firstDayOfWeek':1  }"
					value-format="yyyy-MM-dd"
					placeholder="选择周"
					format="yyyy 第 WW 周"
					style="width: 150px;"
					@change="datePickerChage"
					:size="moduleSize"
				/>
				-
				<el-date-picker
					key="weekrange2"
					v-model="dataForm.dateEnd"
					type="week"
					:picker-options="{ disabledDate: time => datePickerDisable(time, dataForm.dateStart, '<') || weekRangeNum(time, dataForm.dateStart), 'firstDayOfWeek':1  }"
					value-format="yyyy-MM-dd"
					placeholder="选择周"
					format="yyyy 第 WW 周"
					style="width: 150px;"
					@change="datePickerChage"
					:size="moduleSize"
				/> -->
				<el-date-picker
					key="weekrange1"
					v-model="weekValue1"
					type="week"
					:picker-options="{ disabledDate: time => datePickerDisable(time, weekValue2, '>='), 'firstDayOfWeek':1 }"
					value-format="yyyy-MM-dd"
					placeholder="选择周"
					format="yyyy 第 WW 周"
					style="width: 150px;"
					@change="weekRan"
					:size="moduleSize"
				/>
				-
				<el-date-picker
					key="weekrange2"
					v-model="weekValue2"
					type="week"
					:picker-options="{ disabledDate: time => datePickerDisable(time, weekValue1, '<') || weekRangeNum(time, dataForm.dateStart) , 'firstDayOfWeek':1 }"
					value-format="yyyy-MM-dd"
					placeholder="选择周"
					format="yyyy 第 WW 周"
					@change="weekRan"
					style="width: 150px;"
					:size="moduleSize"
				/>
			</template>
			
			<template v-else-if="dateType == 'monthrange'">
				<el-date-picker
					key="monthrange"
					v-model="dataForm.rangeDate"
					type="monthrange"
					placeholder="选择月度"
					:picker-options="{ disabledDate: time => monthDisableCheck(time), onPick: monthOnPick }"
					value-format="yyyy-MM-dd HH:mm:ss"
					start-placeholder="开始月度"
					end-placeholder="结束月度"
					format="yyyy 年 MM 月"
					style="width: 300px;"
					:size="moduleSize"
					@change="datePickerChage(1)"
				/>
			</template>

			<template v-else-if="dateType == 'yearrange'">
				<el-date-picker
					key="yearrange1"
					v-model="dataForm.dateStart"
					type="year"
					placeholder="选择年度"
					value-format="yyyy"
					format="yyyy 年"
					style="width: 120px;"
					@change="yearRan"
					:size="moduleSize"
				/>
				-
				<el-date-picker
					key="dateEnd"
					v-model="dataForm.dateEnd"
					type="year"
					placeholder="选择年度"
					value-format="yyyy"
					format="yyyy 年"
					style="width: 120px;"
					@change="yearRan"
					:size="moduleSize"
				/>
			</template>
		</div>
	</div>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
export default {
	name: 'search-form-date',
	model: {
		prop: 'curData',
		event: 'change'
	},
	props: {
		curData: { required: true, type: Object } /* v-modal 绑定数据... */,
		isHistory: { type: Boolean, default: true } /* 是否可以选择未来时间 */,
		noList: { type: Array, default: () => [] } /* 选择不展示的列表数据 */,
		outObj: { type: Object, default: () => ({ s: 'start', e: 'end', t: 'type' }) } /*, 输出模块字段定义 */,
		moduleSize: { type: String, default: '--' }
	},
	data() {
		var now = new Date();
		return {
			btnList: [
				{ value: 1, name: '按日', dateType: 'daterange' },
				{ value: 2, name: '按周', dateType: 'weekrange' },

				{ value: 3, name: '按月', dateType: 'monthrange' },
				{ value: 4, name: '按年', dateType: 'yearrange' },
				// { value: 5, name: '季度', dateType: 'quarrange' },
				// { value: 6, name: '半年', dateType: 'halfrange' }
			],
			curType: 1,
			weekValue1:'',
			weekValue2:'',
			dateType: '',
			monthDisableDate: {},
			dataForm: {
				date: '',
				rangeDate: [],
				dateStart:'',
				dateEnd:'',
			}
		};
	},
	watch: {
		curType: {
			immediate: true,
			handler(newVal, oldVal){
				if (newVal == 1) this.dateType = `daterange`;
				else if (newVal == 2) this.dateType = `weekrange`;
				else if (newVal == 3) this.dateType = `monthrange`;
				else if (newVal == 4) this.dateType = `yearrange`;
			}
		},

		curData: {
			immediate: true,
			handler(newVal, oldVal){
				// 外部入参处理
				if( Object.keys(newVal).length != 0) {
					if (newVal.type)  this.curType = newVal.type
					if(newVal.dateRange && newVal.dateRange.beginTime){
						this.dataForm.rangeDate = [newVal.dateRange.beginTime, newVal.dateRange.endTime] 
					}else{
						let data={}
						var currentDateStamp = new Date().getTime();
						var date = new Date(currentDateStamp-86400000*7); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
						let Y = date.getFullYear() + '-';
						let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
						let D = date.getDate() + ' ';

						var date2 = new Date(currentDateStamp-86400000*1); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
						let Y2 = date2.getFullYear() + '-';
						let M2 = (date2.getMonth() + 1 < 10 ? '0' + (date2.getMonth() + 1) : date2.getMonth() + 1) + '-';
						let D2 = date2.getDate() + ' ';
						var start = Y + M + D +'00:'+'00:'+'00'
						var end = Y2 + M2 + D2 +'23:'+'59:'+'59'
						this.dataForm.rangeDate = [start + '',end + ''] 
						this.curData.dateRange.beginTime=start + ''
						this.curData.dateRange.endTime=end + ''
					}
				}
			}
		}
	},
	computed: {
		showBtnList: {
			get(){
				return this.btnList.filter(e => !this.noList.includes(+e.value))
			},
			set(val){
				this.curType = val[0]['value']
			}
		},
	},
	mounted() {
	},
	created(){
		this.changeTimeType();
	},
	methods: {
		changeTimeType(){
			let data={}
			var currentDateStamp = new Date().getTime();
			// if(curType=1){
			data = {start:this.timestampToTime(currentDateStamp-86400000*15),end:this.timestampToTime(currentDateStamp-86400000*1)}
			this.dataForm.start = data.start;
			this.dataForm.end = data.end;
			var returnData={
				cType:1,
				beginTime:data.start,
				endTime:data.end,
			}
			
			this.curData.dateRange.beginTime=data.start
			this.curData.dateRange.endTime=data.end
			this.dataForm.rangeDate = [ this.curData.dateRange.beginTime ,this.curData.dateRange.endTime] 
			this.$emit('child',returnData)
		},
		clear() {
			this.dataForm = cloneDeep(this.$options.data().dataForm);

			this.$emit('change', { type: this.curType, dateRange: null });
		},
		timestampToTime(timestamp) {
  			var date = new Date(timestamp); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
			let Y = date.getFullYear() + '-';
			let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
			let D = date.getDate() + ' ';
			return Y + M + D+''+'00:'+'00:'+'00';
		},
		weekRan(){
			let data={}
			if(this.weekValue1) data.start =this.getFirstDayOfWeek2(new Date(this.weekValue1))
			if(this.weekValue2) data.end = this.getFirstDayOfWeek1(new Date(this.weekValue2))
			  var returnData={
				cType:2,
				beginTime:data.start,
				endTime:data.end,
			  }
			  if(data.start && data.end){
			  		this.$emit('child',returnData);
			  }

		},
		//type为字符串类型,有两种选择,"s"代表开始,"e"代表结束,dates为数字类型,不传或0代表本周,-1代表上周,1代表下周
		getweeks(type, dates) {
			var now = new Date();
			var nowTime = now.getTime();
			var day = now.getDay();
			var longTime = 24 * 60 * 60 * 1000;
			var n = longTime * 7 * (dates || 0);
			if (type == "s") {
				var dd = nowTime - (day - 2) * longTime + n;
			};
			if (type == "e") {
				var dd = nowTime + (7 - day) * longTime + n;
			};
			dd = new Date(dd);
			var y = dd.getFullYear();
			var m = dd.getMonth() + 1;
			var d = dd.getDate();
			m = m < 10 ? "0" + m: m;
			d = d < 10 ? "0" + d: d;
			var day = y + "-" + m + "-" + d;
			return day;
},
		yearRan(){
			console.log(this.dataForm.dateStart,9997)
			console.log(this.dataForm.dateEnd,9999)
			  var returnData={
				cType:4,
				beginTime:this.dataForm.dateStart+'-01-01 00:00:00',
				endTime:this.dataForm.dateEnd + '-12-31 23:59:59',
			  }
			  if(this.dataForm.dateEnd && this.dataForm.dateStart){
			  		this.$emit('child',returnData);
			  }
		},

		/* 12周数量限制 */
		weekRangeNum(time, date) {
			if (!date) return false;
			if (time.getTime() > new Date(date).getTime() + 8.64e7 * 85) return true;
			return false;
		},
		/* start使用  >=;   end  < */
		/* 参数中不应用 >= 或 < 符号. 应用参数传入的位置不同来控制参数 */
		datePickerDisable(time, date, com = '>=') {
			if (this.isHistory && time.getTime() > Date.now()) return true;
			if(com=='>=') {
				// 开始周
			}
			if (date) {
				if(com=='>=') {
					// 开始周
					let endDate = this.getFirstDayOfWeek1(new Date(date))
					return eval(`${time.getTime()} ${com} ${new Date(endDate).getTime()}`);
				}else {
					// 结束周
					let startDate = this.getFirstDayOfWeek2(new Date(date))
					return eval(`${time.getTime()} ${com} ${new Date(startDate).getTime()}`);
				}
			} 
			return false;
		},
		outMonth() {
			var { monthDateS = 1, monthDateE } = this.dataForm;
			var mOptions = { 1: '01-01', 2: '04-01', 3: '07-01', 4: '10-01' },
				mEndOptions = { 1: '03-31', 2: '06-30', 3: '06-30', 4: '12-31' },
				yOptions = { 1: '01-01', 2: '07-01' },
				yEndOptions = { 1: '06-30', 2: '12-31' };
			var s, e;

			if (!monthDateS) monthDateS = 1;

			return { s, e };
		},
		datePickerChage(int) {
			/* 当前数据变化 */
			var data = {};
			var cType = this.curType;
			var { date = '', dateStart = '', dateEnd = '', rangeDate = [], monthDateS, monthDateE } = this.dataForm;
			var monthDate = this.outMonth();

			/* 准备重构数据整合............  可复用性高. */
			/* 1: 单日,2: 单周,3: 年度,4: 月度,99: 自定义 */
			/* 判断是否是范围选择 */
			if (cType == 1 && rangeDate) {
				data = { start: rangeDate[0], end: rangeDate[1] };
			} else if (cType == 2) {
				if (dateStart) data.start = this.getFirstDayOfWeek(new Date(dateStart));
				if (dateEnd) data.end = this.getFirstDayOfWeek(new Date(dateEnd));
				// data = { start: dateStart, end: dateEnd };
			} else if (cType == 4) {
				if (dateStart) data.start = `${dateStart}-01-01 00:00:00`
				if (dateEnd) data.end = `${dateEnd}-01-01 00:00:00`
			} else if (cType == 3 && rangeDate) {
			
				if(int){
					var mon = rangeDate[1].slice(5,7)
					var year = rangeDate[1].slice(0,4)
					var lastDay= new Date(year,mon,0).getDate()
				console.log(rangeDate[1]	,"222222222222222222");
					rangeDate[1]=year+'-'+mon+'-'+lastDay+' 00:00:00'
					console.log(rangeDate[1]	,"222222222222222222");
				}

				data = { start: rangeDate[0], end: rangeDate[1] };
				
			} 
			var outData = {
				...this.curData,
				dateRange: { beginTime: data.start, endTime: data.end }
	  };
	  var returnData={
		  cType:this.curType,
		  beginTime:data.start,
		  endTime:data.end,
	  }
      this.dataForm.dateStart = data.start
      this.dataForm.dateEnd = data.end
			
			if (data.start && data.end) this.$emit('searchFinish', outData);
			this.$emit('change', outData);
			this.$emit('child',returnData);
			
		},
		monthDisableCheck(time) {
			if (this.isHistory && time.getTime() > Date.now()) return true;
			var { minDate } = this.monthDisableDate
			if (minDate) {
				var cur = new Date(minDate).getTime()
				var timeN = time.getTime()
				
				var month12 = 365 * 8.64e7;
				if (cur - month12 + 31 * 8.64e7 >= timeN) return true
				else if (cur + month12 - 30 * 8.64e7 < timeN) return true
			}
			
			return false;
		},
		getFirstDayOfWeek(date) {
		    var day = date.getDay() || 7;
		    var out = new Date(date.getFullYear(), date.getMonth(), date.getDate() +1 - day);
			return `${out.getFullYear()}-${out.getMonth() + 1}-${out.getDate()} 00:00:00`
		},
		getFirstDayOfWeek1(date){
			var day = date.getDay() || 7 ;
			var out = new Date(date.getFullYear(),date.getMonth(),date.getDate()+7-day);
			return `${out.getFullYear()}-${out.getMonth() + 1}-${out.getDate()} 00:00:00` 
		},
		getFirstDayOfWeek2(date){
			var day = date.getDay() || 7 ;
			var out = new Date(date.getFullYear(),date.getMonth(),date.getDate()-1);
			return `${out.getFullYear()}-${out.getMonth() + 1}-${out.getDate()} 00:00:00` 
		},
		getFirstDayOfWeek3(date){
			var day = date.getDay() || 7 ;
			var out = new Date(date.getFullYear(),date.getMonth(),date.getDate()+7-day);
			return `${out.getFullYear()}-${out.getMonth() + 2}-${out.getDate()} 00:00:00` 
		},
		getFirstDayOfWeek4(date){
			var day = date.getDay() || 7 ;
			var out = new Date(date.getFullYear(),date.getMonth(),date.getDate()-1);
			return `${out.getFullYear()}-${out.getMonth() + 2}-${out.getDate()} 00:00:00` 
		},
		getFirstDayOfWeek5(date) {
		    var day = 7;
		    var out = new Date(date.getFullYear(), date.getMonth(), date.getDate() +1 - day);
			return `${out.getFullYear()}-${out.getMonth() + 1}-${out.getDate()} 00:00:00`
		},
		monthOnPick(date) {
			if (!date.mxaDate) this.monthDisableDate = date
			else this.monthDisableDate = {}
		},
		reset(){
			this.curType=1;
			this.changeTimeType(); 
			this.curData.dateRange.beginTime=this.dataForm.start + '';
			this.curData.dateRange.endTime=this.dataForm.end + '';

		},
		//获取本周
		getWeekDays(date){
			let firstDay=new Date(date.getFullYear(),0,1)
			let dayOfWeek=firstDay.getDay()
			let spendDay=1
			if(dayOfWeek!=0){
				spendDay=7-dayOfWeek+1
			}
			firstDay=new Date(val.getFullYear(),0,1+spendDay)
			let d=Math.ceil((val.valueOf()-firstDay.valueOf())/86400000)
			let result=Math.ceil(d/7)
			let year = val.getFullYear()
			let week =result+2
			return year+'第'+week+'周'			
		},
		//获取本月

		/* 单选change */
		radioChange() {
			this.dataForm.rangeDate=[]
			let data={}
				// var date=new Date()
				var date=new Date()
				var nowTime=date.getTime();
				var day=date.getTime()||7;
				var y=date.getFullYear()
				var m=date.getMonth()+1
				var d=date.getDate()
				var week= y+'-'+m+'-'+d+' '+'00'+':'+'00'+':'+'00'
				var monthStart=y+'-'+m+'-'+'01'+' '+'00'+':'+'00'+':'+'00'
				var monthEnd=y+'-'+m+'-'+d+' '+'00'+':'+'00'+':'+'00'
		
			if(this.curType==1){
				this.changeTimeType()
			}else if(this.curType==2){
				this.weekValue1=this.getweeks("s",-1),
				this.weekValue2=this.getweeks("e",-1),
				this.weekRan()
			}else if(this.curType==3){
				// data.start =monthStart
				// data.end = monthEnd
				this.dataForm.rangeDate[0]=monthStart;
				this.dataForm.rangeDate[1]=monthEnd
				this.datePickerChage()
			}else if(this.curType==4){
				this.dataForm.dateStart=y+''
				this.dataForm.dateEnd=y+''
				this.yearRan()
			}
			this.$emit('change', { ...this.curData, [this.outObj.t]: this.curType })
			// this.clear()
		}
	}
};
</script>

<style lang="scss">
.el-select .el-input {
	width: 100% !important;
}
</style>

使用
<template>
	<div>
	<SearchFormDate
          :curData="curData"
          ref="resetCommon"
          @child="child"
        ></SearchFormDate>
	</div>
</template>
<script>
import SearchFormDate from "@/components/SearchFormDate";
export default {
  components: {
    SearchFormDate,
  },
  data() {
  return {
  	curData: {
        type: 1,
        dateRange: {
          beginTime: "",
          endTime: "",
        },
      },
      params: {
        queryType: 1,
        startDate: "",
        endDate: "",
      },
  }
  },
  methods: {
  child(objArgu, weekTime) {
      this.objArgu = objArgu;
      this.params.queryType = objArgu.cType;
      this.params.startDate = objArgu.beginTime;
      this.params.endDate = objArgu.endTime;
      this.weekTime = weekTime;
      this.getDataList();
    },
 }
  }
</script>


这篇关于基于elementui的年月日周时间控件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程