<template>
<div id = "myDate" >
<el-select v-model="yearsModel" @change="dateChange(1)" placeholder="请选择" >
<el-option
v-for="item in years"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
<el-select v-model="monthsModel" @change="dateChange(2)" placeholder="请选择" >
<el-option
v-for="item in months"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
<el-select v-model="daysModel" @change="dateChange(3)" placeholder="请选择" >
<el-option
v-for="item in days"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</div>
</template>
<script>
import {mapMutations} from 'vuex'
export default {
props: {
},
data() {
return {
yearsModel:null,
years:[],
monthsModel:null,
months:[],
daysModel:null,
days:[],
}
},
created() {
this.init();
},
methods: {
...mapMutations('app',['changeDate']),
init(){
var myDate = new Date;
var year = myDate.getFullYear();//获取当前年
var month = myDate.getMonth()+1;//获取当前月
var day = myDate.getDate();//获取当前日
this.initSelectYear(year)
this.initSelectMonth();
this.initSelectDay(year,month);
this.yearsModel = year;
this.monthsModel = month;
this.daysModel = day;
let obj ={year:this.yearsModel,month:this.monthsModel,day:this.daysModel }
this.$parent.dateChange(obj);
},
initSelectYear(year){
this.years = [];
for(let i=0;i<30;i++){
this.years.push({value:(year - i),label:(year - i)+ "年"});
}
},
initSelectMonth(){
this.months = [];
this.months.push({value:0,label:"全部"});
for(let i=1;i<=12;i++){
this.months.push({value:i,label:i+ "月"});
}
},
initSelectDay(year,month){
var maxDay = this.getMaxDay(year,month);
this.days = [];
this.days.push({value:0,label:"全部"});
for(var i=1;i<=maxDay;i++){
this.days.push({value:i,label:i+ "日"});
}
},
dateChange(type){
//1年 2月 3日
if(type == 1||type == 2){
if(this.monthsModel == 0){
// this.daysModel = 0;
this.initSelectDay(this.yearsModel,1);
}else{
this.initSelectDay(this.yearsModel,this.monthsModel);
}
}
//操作父组件方法
let day=String(this.daysModel)
if(day.split('').length==1){
day='0'+this.daysModel
}
let month=String(this.monthsModel)
if(month.split('').length==1){
month='0'+this.monthsModel
}
let obj ={year:this.yearsModel,month,day:day }
this.$parent.dateChange(obj);
},
getMaxDay(year,month){
var new_year = year; //取当前的年份
var new_month = month++;//取下一个月的第一天,方便计算(最后一天不固定)
if(month>12) //如果当前大于12月,则年份转到下一年
{
new_month -=12; //月份减
new_year++; //年份增
}
var new_date = new Date(new_year,new_month,1);//取当年当月中的第一天
return (new Date(new_date.getTime()-1000*60*60*24)).getDate();//获取当月最后一天日期
}
}
}
</script>
<style lang="scss">
#myDate{
.el-select{
margin-right: 15px;
.el-input__inner{
font-size: 16px;
width: 149px;
height: 35px;
background-image: linear-gradient(90deg,
#0d3d4e 0%,
#102b3f 43%,
#121930 100%),
linear-gradient(
#00ffff,
#00ffff);
background-blend-mode: normal,
normal;
border-radius: 5px;
border: solid 1px #087381;
}
}
}
</style>