template部分,这里的value1,value2的值为我们所选周的星期一,为格林尼治时间的格式; date1, date2为周选择器的value对应的日期,date1取当周的星期一(起始日期),date2取当周的星期日(结束日期),weekNum为周数
computed: {
weekNum() {
return Math.round((this.value2 - this.value1) / (24 * 60 * 60 * 1000 * 7)) + 1
},
},
data() {
return {
value1: null,
value2: null,
date1: '',
date2: '',
pickerOptions: {
firstDayOfWeek: 1,
disabledDate: (time) => this.getDisabledDate(time, 'start'),
shortcuts: [{
text: '近1周',
onClick: (picker) => {
this.onWeekChange(picker, 1)
}
}, {
text: '近4周',
onClick: (picker) => {
this.onWeekChange(picker, 4)
}
}, {
text: '近12周',
onClick: (picker) => {
this.onWeekChange(picker, 12)
}
}]
}
}
},
created里面来设置一个起始日期,这里将value设为了最近一周的周一,
created() {
this.value1 = this.value2 = moment().isoWeekday(-5).toDate()
},
watch: {
value1() {
if (!this.value1) return
if (this.value1 >= this.value2) { // 保证value2大于value1
this.value2 = this.value1
}
this.date1 = moment(this.value1.getTime() - 24 * 60 * 60 * 1000).format('YYYY-MM-DD')
this.onValueChange() // 这里为我们希望value改变时触发的方法
},
value2() {
if (!this.value2) return
this.date2 = moment(this.value2.getTime() + 5 * 24 * 60 * 60 * 1000).format('YYYY-MM-DD')
this.onValueChange()
},
}
methods: {
onWeekChange(picker, k) { // 选中近k周后触发的操作
this.value1 = moment().isoWeekday(-(5 + (k - 1) * 7)).toDate()
this.value2 = moment().isoWeekday(-5).toDate() //value2与k值无关,因为它总是为最近一周的周一
this.$forceUpdate() // 这里如果不强制更新视图,会出现value值改变而视图中的第几周和日期无变化的情况
},
}