JavaScript 自定义年月日选择下拉框select选择的日期方法vue实现

JavaScript 自定义选择年月日,需求如下图所示:

JavaScript 自定义年月日选择下拉框select选择的日期方法vue实现_第1张图片

代码示例如下:

js:

export default {
	data() {
		return {
		        year:[],
			month:[],
			day:[],
			formData:{
				year:2019,
				month:1,
				day:1
			},
		}
	},
	methods: {
		init(){
		  this.getYear();
		  this.getMonth();
		  this.getDay();
		},
		getYear(){//获取年
		  let date = new Date;
		  let current_year = date.getFullYear();
		  for (let i = 0; i < 100; i++) {
		    let y = current_year - i;
			this.year.push(y);
		  }
		},
		getMonth(){//获取月
		  for (let i = 1; i < 13; i++) {
			this.month.push(i);
		  }
		},
		getDay(){//获取日
		  this.day = [];
		  let day = this.getDaysInMonth(this.formData.year, this.formData.month)
		  for (let i = 1; i <= day ; i++) {
		      this.day.push(i);
		  }
		},
		getDaysInMonth(year, month) {//获取某个月的天数
	          month = parseInt(month, 10);
		  let d = new Date(year, month, 0);
		  return d.getDate();
		},
		padding0(num, length) {//数字前填充0方法
		   for(let len = (num + "").length; len < length; len = num.length) {
			  num = "0" + num;            
		   }
		   return num;
		},
                submit(){//提交      
                    let birthday = this.formData.year +"-" + this.padding0(this.formData.month,2) +"-" + this.padding0(this.formData.day,2);

		    let cur_date = new Date();
		    if(cur_date < new Date(birthday)){
			    alert("请选择小于今天的年月日");
			    return;
		    }
                    console.log(birthday);//birthday就是得到的最终的日期,格式为2019-01-01
                }
	 },
	 mounted() {
		this.init();
	 }
}

 

你可能感兴趣的:(Vue,JavaScript,Vue,Javascript)