解决了使用ElementUI日期选择器时,选择“2024第1周”这一特殊时间段所触发的change事件返回时间的特殊情况处理问题。

  • 当选择某周后,自动计算该周的特殊日期范围:
    • 将ElementUI返回的周一日期减1天,得到上周日作为起始日
    • 从起始日加6天,得到本周六作为结束日
  • 选示例:选择"2024 第 1 周"时
    • 原始周一日期:2023-12-31(ElementUI默认返回周日)
    • 计算后范围:2024-01-06(周日)至 2025-03-22(周六)

代码:

复制代码
<template>
  <div>
    <el-date-picker
      v-model="value1"
      type="week"
      format="yyyy 第 WW 周"
      placeholder="选择周"
      @change="handleDateChange"
    />
    <div v-if="selectedYear && selectedWeekStart && selectedWeekEnd">
      <p>选中的年份: {{ selectedYear }}</p>
      <p>选中周的第一天(减一): {{ selectedWeekStart }}</p>
      <p>选中周的最后一天(减一): {{ selectedWeekEnd }}</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value1: '', // 绑定的值
      selectedYear: null, // 选中的年份
      selectedWeekStart: null, // 选中周的第一天(减一)
      selectedWeekEnd: null // 选中周的最后一天(减一)
    }
  },
  methods: {
    handleDateChange(value) {
      if (value) {
        const selectedDate = new Date(value)
        // 计算周一的日期(ElementUI默认返回周一的日期)
        const startDate = new Date(selectedDate)

        // 对周一的日期减一,得到上周日
        startDate.setDate(startDate.getDate() - 1)

        // 计算周日的日期
        const endDate = new Date(startDate)
        endDate.setDate(startDate.getDate() + 6) // 从上周日开始加6天,得到本周六

        this.selectedYear = startDate.getFullYear()
        this.selectedWeekStart = this.formatDate(startDate)
        this.selectedWeekEnd = this.formatDate(endDate)
      } else {
        // 重置选中的日期信息
        this.selectedYear = null
        this.selectedWeekStart = null
        this.selectedWeekEnd = null
      }
    },
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始,需要加1
      const day = String(date.getDate()).padStart(2, '0') // 直接使用 date.getDate(),不需要减1
      return `${year}-${month}-${day}`
    }
  }
}
</script>

效果图:

相关推荐
进击的尘埃4 分钟前
Vue3 中 emit 能 await 吗?事件机制里的异步陷阱
javascript
青青家的小灰灰13 分钟前
告别 Prop Drilling:Context API 的陷阱、Reducer 模式与原子化状态库原理
前端·javascript·react.js
叶智辽15 分钟前
【Three.js后期处理】如何让你的场景拥有电影级调色
前端·three.js
进击的尘埃16 分钟前
CSS 变量 + 主题切换:从 CSS-in-JS 回归原生方案的实践之路
javascript
前端付豪17 分钟前
Nest 项目小实践之前端注册登陆
前端·node.js·nestjs
wuhen_n17 分钟前
Suspense:异步组件加载机制
前端·javascript·vue.js
大雨还洅下17 分钟前
前端JS: ES6新特性
前端
wuhen_n18 分钟前
Teleport:渲染到任意DOM节点
前端·javascript·vue.js
进击的尘埃19 分钟前
组合式函数的设计模式:如何写出真正可复用的 Vue3 Composables
javascript
Moment19 分钟前
想要长期陪伴你的助理?先从部署一个 OpenClaw 开始 😍😍😍
前端·后端·github