废话不多说,直接上代码

created(){

	// 获取时间段内的年月
	this.getMonthBetween('2020-09-017','2022-06-01')
	
	// 根据年月获取天数
	this.updateCalendar({
		year: '2020', 
		month: '9'
	})

},

methods: {
		// 选择月份
		changeMonth(month,index){
			this.day_idx = -1
			this.month_idx = index
			this.updateCalendar(month)
		},
		// 选择天
		changeDay(day,index){
			if(!day){return false}
			this.day_idx = index
		},
		// 获取两个时间段之间的年月
		getMonthBetween(start,end){ 
			let s = start.split("-"),
				e = end.split("-"),
				min = new Date(),
				max = new Date();  
				
			min.setFullYear(s[0],s[1]);  
			max.setFullYear(e[0],e[1]);  
			let curr = min;  
			
			while(curr <= max){  
				let year = curr.getFullYear(), 
					month = curr.getMonth(),
					str= {
						year,
						month: month==0?12:month
					}
				this.months.push(str);  
				curr.setMonth(month+1);
			}
		 },
		  // 为了获得每个月的日期有多少,我们需要判断 平年闰年[四年一闰,百年不闰,四百年再闰]
		 isLeapYear (year)  {
			return (year % 400 === 0) || (year % 100 !== 0 && year % 4 === 0);
		  },
		  // 获得每个月的日期有多少,注意 month - [0-11]
		getMonthCount (year, month)  {
		    let arr = [
		      31, null, 31, 30, 
		      31, 30, 31, 31,
		      30, 31, 30, 31
		    ];
		    let count = arr[month] || (this.isLeapYear(year) ? 29 : 28);
		    return Array.from(new Array(count), (item, value) => value + 1);
		  },
		  // 3.获得某年某月的 1号 是星期几,这里要注意的是 JS 的 API-getDay() 是从 [日-六](0-6),返回 number
		    getWeekday  (year, month){
		      let date = new Date(year, month, 1);
		      return date.getDay();
		    },
		  // 4.获得上个月的天数
		  getPreMonthCount (year, month){
		      if (month === 0) {
		        return this.getMonthCount(year - 1, 11);
		      } else {
		        return this.getMonthCount(year, month - 1);
		      }
		    },
		// 5.获得下个月的天数
		  getNextMonthCount (year, month)  {
		    if (month === 11) {
		      return this.getMonthCount(year + 1, 0);
		    } else {
		      return this.getMonthCount(year, month + 1);
		    }
		  },
		
		// 根据年月获取天数
		updateCalendar (months) {
		    let {year, month} = months,
				currentMonth = this.getMonthCount(year, month),
				preMonth = this.getPreMonthCount(year, month),
				nextMonth = this.getNextMonthCount(year, month),
				whereMonday = this.getWeekday(year, month);
				whereMonday = whereMonday === 0 ? 7 : whereMonday
			// 上月
		    let preArr = preMonth.slice(-1 * whereMonday);
				preArr = this.setEmptyArr(preArr.length);
			// 下月
		    let nextArr = nextMonth.slice(0, 42 - currentMonth.length - whereMonday);
				nextArr = this.setEmptyArr(nextArr.length)
			
		    this.days = [].concat(preArr, currentMonth, nextArr);
		  },
		 
		// 除去前后月的天数
		setEmptyArr(len){
			let arr=[]
			for(let i=0; i <len; i++){
				arr = ['',...arr]
			}
			return arr.length===7?[]:arr
		},
}

效果如图:
在这里插入图片描述

Logo

前往低代码交流专区

更多推荐