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

效果图:

相关推荐
海石6 小时前
去到比北方更北的地方—2025年终总结
前端·ai编程·年终总结
一个懒人懒人6 小时前
Promise async/await与fetch的概念
前端·javascript·html
Mintopia6 小时前
Web 安全与反编译源码下的权限设计:构筑前后端一致的防护体系
前端·安全
输出输入7 小时前
前端核心技术
开发语言·前端
Mintopia7 小时前
Web 安全与反编译源码下的权限设计:构建前后端一体的信任防线
前端·安全·编译原理
林深现海7 小时前
Jetson Orin nano/nx刷机后无法打开chrome/firefox浏览器
前端·chrome·firefox
黄诂多7 小时前
APP原生与H5互调Bridge技术原理及基础使用
前端
前端市界7 小时前
用 React 手搓一个 3D 翻页书籍组件,呼吸海浪式翻页,交互体验带感!
前端·架构·github
文艺理科生7 小时前
Nginx 路径映射深度解析:从本地开发到生产交付的底层哲学
前端·后端·架构
千寻girling7 小时前
主管:”人家 Node 框架都用 Nest.js 了 , 你怎么还在用 Express ?“
前端·后端·面试