解决了使用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>

效果图:

相关推荐
张元清23 分钟前
React useTimeout Hook:声明式 setTimeout 与自动清理 (2026)
javascript·react.js
禁止摆烂_才浅1 小时前
JavaScript 类型判断:instanceof 与 constructor 原理深度解析
前端·javascript·面试
gezg1 小时前
DeepSeek Harness 插件:Excel 拖进输入框,AI 自己去读文件
前端·ai编程
Asize1 小时前
HTTP 明明无状态,登录态怎么就保住了——React + Zustand + JWT 鉴权全流程拆解
前端·javascript
两只羊ovo1 小时前
MCP:AI 界的 USB-C,把模型和世界「插」起来
前端
Darling噜啦啦1 小时前
JWT 登录鉴权全链路:从 Zustand 状态管理到 Axios 拦截器,彻底搞懂前端鉴权工程
前端
可涵不会debug1 小时前
LangChain 示例选择器(Example selectors)完整基础概念解读
服务器·前端·数据库
Csvn1 小时前
😱 React `<StrictMode>`:为什么 useEffect 被调用了两次?别慌,这是特性不是 bug
前端
Asize2 小时前
2 道大厂面试题:TS 工具类型我懂了,CSS 3 列布局把我问住了
前端·css·typescript
胡萝卜术2 小时前
从"氛围编程"到规范驱动:两次创造如何让 AI 协作从碰运气变成工程流水线
前端·面试·github