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

效果图:

相关推荐
yu俞娥宝37 分钟前
Codex官网前端可抄吗?技术拆解、风险边界与合规借鉴方案
前端
捧 花1 小时前
FastAPI 基础语法:从一个完整接口理解 Web API 的设计
前端·python·fastapi·middleware
Hilaku1 小时前
一行 CSS 新特性干掉 20 行 JavaScript ?
前端·javascript·程序员
风月说与山鬼1 小时前
JS闭包详解
开发语言·javascript
JarvanMo1 小时前
AI 写代码暴增 161 倍,移动开发有没有变得更差?
前端
梦曦i1 小时前
RouterLink v2.5.0:H5端原生能力全面回归
前端·uni-app
小林ixn2 小时前
React + Zustand + JWT:从零实现登录鉴权与请求拦截
前端·react.js·前端框架
葡萄城技术团队2 小时前
下拉多选类型单元格:在 SpreadJS 里接入 xm\-select
前端
粥里有勺糖2 小时前
视野修炼-技术周刊第130期 | 光影效果
前端·javascript·github
小岛前端2 小时前
AI Skills 已经封神,但新的问题却越来越严重!
前端·后端·github