背景

公司有个用vue + element ui 开发的我的项目须要实现这样一个需要:以周为周期抉择一个工夫范畴,并显示为日期的格局,能够快捷抉择近1周,近周围……

antd中是有周范畴选择器的,悲催的是element ui没有,并且也没找到相似的,只好本人封一个

下图为antd

下图为element ui,只有日期范畴和月范畴,偏偏没有周范畴……

思路

有两种思路

  1. 管制两个独自的周选择器实现联动
  2. 革新日期选择器,选中某个日期时对应的整行变色

这里最终选用了第一种思路,用到了moment库,应用装置很简略,可自行装置


实现成果:

template局部,这里的value1,value2的值为咱们所选周的星期一,为格林尼治工夫的格局; date1, date2为周选择器的value对应的日期,date1取当周的星期一(起始日期),date2取当周的星期日(完结日期),weekNum为周数

实现代码

  1. template构造:

     <div class="block">   <span style="margin-right:10px">周期抉择: </span>   <el-date-picker     v-model="value1"     type="week"     format="yyyy 第 WW 周"     placeholder="抉择周"     :picker-options="pickerOptions"     style="width: 180px"   >   </el-date-picker>   至   <el-date-picker     v-model="value2"     type="week"     format="yyyy 第 WW 周"     placeholder="抉择周"     :picker-options="pickerOptions"     style="width: 180px"   >   </el-date-picker>   <span v-if="value1&&value2" style="margin-left: 10px">     {{ date1 }} 至 {{ date2 }}, 共 {{ weekNum }} 周   </span>  </div>

    weekNum的计算:

computed: {    weekNum() {      return Math.round((this.value2 - this.value1) / (24 * 60 * 60 * 1000 * 7)) + 1    },  },
  1. data:
  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)          }        }]      }    }  },
  1. created外面来设置一个起始日期,这里将value设为了最近一周的周一,
  created() {    this.value1 = this.value2 = moment().isoWeekday(-5).toDate()  },
  1. 侦听value1, value2,当它们变动时更新日期
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()    },}
  1. 选中近k周的后触发的操作
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值扭转而视图中的第几周和日期无变动的状况    },}