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

效果图:

相关推荐
invicinble3 小时前
数字系统--c端数字环境入口和操作系统
前端
求道於盲3 小时前
异步编程中的 Future
前端
Z兽兽3 小时前
HBuilder打包web地址的apk,更新dist后如何自动清缓存
前端·android应用打包
Hilaku4 小时前
Bun 真的能取代 Node.js 吗?
前端·javascript·程序员
奔跑的卡卡4 小时前
线上Web异常发现为什么总是滞后?一套自研Web实时异常分析监控系统整体架构拆解
前端·web安全·架构
梦曦i4 小时前
create-uni-app v1.1.0:结构化生成,工程骨架更规范
前端·uni-app
流光D4 小时前
AI时代,搭建 web 站点并配置 nginx 反向代理流程
运维·服务器·前端·人工智能·nginx·ai·ai编程
PBitW4 小时前
Travel Planner — 智能旅行行程规划助手
前端·后端
梨想橙汁4 小时前
CSS Grid 网格布局:二维布局神器,轻松实现复杂网页排版
前端·css
lhldsg4 小时前
酒吧点餐小程序开发:从需求分析到技术落地实战
java·前端·小程序·架构·交友