element的datepicker日期选择器选择周一到周日并实现上一周和下一周
实现效果
页面初始化效果
点击上一周
点击下一周
实现选择周一和周日过程
1、采用el-date-picker组件,类型使用
week
<el-date-pickerv-model="weeklyDate"type="week"@change="newDateWeekHandle"placeholder="选择周"style="width: 230px"></el-date-picker>
但是范围是从周日开始,从周一开始需要将
firstDayOfWeek
设置为 1
<el-date-pickerv-model="weeklyDate"type="week":picker-options="{'firstDayOfWeek': 1}"@change="newDateWeekHandle"placeholder="选择周"style="width: 230px"></el-date-picker>
2、框里还需要展示周一和周日的范围,设置两个新的属性startDate和endDate
<el-date-picker:format="startDate + ' 至 ' + endDate"v-model="weeklyDate"type="week":picker-options="{'firstDayOfWeek': 1}"@change="newDateWeekHandle"placeholder="选择周"style="width: 230px"></el-date-picker>
根据model属性(默认是星期二),来算出展示的星期一和周期日
newDateWeekHandle(){const now =newDate(this.weeklyDate);const nowTime = now.getTime();const day = now.getDay();const oneDayTime =24*60*60*1000;const mondayTime = nowTime -(day-1)*oneDayTime;const sundayTime = nowTime +(7-day)*oneDayTime;this.startDate =this.$moment(mondayTime).format('YYYY-MM-DD');this.endDate =this.$moment(sundayTime).format('YYYY-MM-DD');},
这里用到了moment.js,需要引入
3、下载moment
npminstall moment --save
为了可以全局使用到,在main.js中全局方法挂载
import moment from'moment'Vue.prototype.$moment = moment
4、选择之后才能展示范围,需要在页面初始化时就给model属性赋值
- 在created中调用getDateWeek方法
- 同时进行计算周一和周日
getDateWeek(){const now =newDate();const nowTime = now.getTime();const day = now.getDay();const oneDayTime =24*60*60*1000;const mondayTime = nowTime -(day-2)*oneDayTime;//默认是周二this.weeklyDate =newDate(mondayTime);this.newDateWeekHandle();},
实现上一周和下一周的切换功能
实际上就是计算model属性值就可以了,通过Date的setDate方法实现日期的相加减,然后根据新得到的日期计算就可以了
[参考文章][https://blog.csdn.net/yangmy_Shy/article/details/91380206]
handleLast(){const last =newDate(this.weeklyDate);
last.setDate(last.getDate()-7);//日期相加减this.weeklyDate = last;this.newDateWeekHandle();},handleNext(){const next =newDate(this.weeklyDate);
next.setDate(next.getDate()+7);this.weeklyDate = next;this.newDateWeekHandle();},
版权归原作者 睡不醒的一天 所有, 如有侵权,请联系我们删除。