element的datepicker日期选择器选择周一到周日并实现上一周和下一周
实现效果
页面初始化效果
点击上一周
点击下一周
实现选择周一和周日过程
1、采用el-date-picker组件,类型使用week
<el-date-picker
v-model="weeklyDate"
type="week"
@change="newDateWeekHandle"
placeholder="选择周" style="width: 230px">
</el-date-picker>
但是范围是从周日开始,从周一开始需要将firstDayOfWeek
设置为 1
<el-date-picker
v-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 = new Date(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
npm install moment --save
为了可以全局使用到,在main.js中全局方法挂载
import moment from 'moment'
Vue.prototype.$moment = moment
4、选择之后才能展示范围,需要在页面初始化时就给model属性赋值
- 在created中调用getDateWeek方法
- 同时进行计算周一和周日
getDateWeek(){
const now = new Date();
const nowTime = now.getTime();
const day = now.getDay();
const oneDayTime = 24*60*60*1000;
const mondayTime = nowTime - (day-2)*oneDayTime;//默认是周二
this.weeklyDate = new Date(mondayTime);
this.newDateWeekHandle();
},
实现上一周和下一周的切换功能
实际上就是计算model属性值就可以了,通过Date的setDate方法实现日期的相加减,然后根据新得到的日期计算就可以了文章来源:https://www.toymoban.com/news/detail-625653.html
[参考文章][https://blog.csdn.net/yangmy_Shy/article/details/91380206]文章来源地址https://www.toymoban.com/news/detail-625653.html
handleLast(){
const last = new Date(this.weeklyDate);
last.setDate(last.getDate()-7);//日期相加减
this.weeklyDate = last;
this.newDateWeekHandle();
},
handleNext(){
const next = new Date(this.weeklyDate);
next.setDate(next.getDate()+7);
this.weeklyDate = next;
this.newDateWeekHandle();
},
到了这里,关于element的datepicker日期选择器选择周一到周日并实现上一周和下一周的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!