关于vue.js:基于element-ui实现一个按周选择时间范围的功能

7次阅读

共计 2024 个字符,预计需要花费 6 分钟才能阅读完成。

背景

公司有个用 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 值扭转而视图中的第几周和日期无变动的状况},
}
正文完
 0