vue+elementui实现12个日历平铺,初始化工作日,并且可点击

css 复制代码
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="年份" prop="holidayYear">
        <el-date-picker
          v-model="queryParams.holidayYear"
          type="year"
          :clearable="false"
          placeholder="选择年"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row>
      <el-button type="primary" @click="submitClickedDates">提交</el-button>

      <div v-for="(cal, index) in defaultCals" :key="index">
        <el-col :span="6">
          <el-calendar :value="cal" class="holiday">
            <template slot="dateCell" slot-scope="{ date, data }">
              <div
                class="holiday-cell"
                v-show="data.type === 'current-month'"
                :id="cal.getMonth() + '-' + data.day"
                @click="selectCalendarDate(cal, data)"
                :style="{ backgroundColor: getCellBackgroundColor(cal, data) }"
              >
                {{ data.day.split("-")[2] }}
              </div>
            </template>
          </el-calendar>
        </el-col>
      </div>
    </el-row>
  </div>
</template>

<script>
export default {
  // name: "temp",
  data() {
    return {
      queryParams: {
        holidayYear: new Date(),
      },
      //设置的月份
      defaultCals: [],
      // 全年已选中的日期
      holidayDate: [],
      clickedDates: [], // 记录点击的日期
      selectedDates: [], // 初始选中的日期数组
    };
  },
  created() {
    //初始化日历
    let nowYear = new Date().getFullYear();
    this.initCalendar(nowYear + 1);

    // 初始化日历
    // let nowYear = new Date().getFullYear();
    // this.currentMonth = new Date(); // 明确初始化this.currentMonth
    // this.initCalendar(nowYear + 1);
  },
  methods: {
    // 根据给定的年份获取一年中周一到周五的日期数组
    getWeekdays(year) {
      const weekdays = [];
      const currentDate = new Date(year, 0, 1); // 设置为给定年份的第一天

      // 遍历一年中的每一天
      while (currentDate.getFullYear() === year) {
        const dayOfWeek = currentDate.getDay();

        // 如果是周一到周五,将日期格式化并添加到数组中
        if (dayOfWeek >= 1 && dayOfWeek <= 5) {
          const formattedDate = `${currentDate.getFullYear()}-${(
            currentDate.getMonth() + 1
          )
            .toString()
            .padStart(2, "0")}-${currentDate
            .getDate()
            .toString()
            .padStart(2, "0")}`;
          weekdays.push(formattedDate);
        }

        // 将日期增加一天
        currentDate.setDate(currentDate.getDate() + 1);
      }

      return weekdays;
    },
    //初始化日历
    initCalendar(year) {
      this.defaultCals = [
        new Date(year, 0, 1),
        new Date(year, 1, 1),
        new Date(year, 2, 1),
        new Date(year, 3, 1),
        new Date(year, 4, 1),
        new Date(year, 5, 1),
        new Date(year, 6, 1),
        new Date(year, 7, 1),
        new Date(year, 8, 1),
        new Date(year, 9, 1),
        new Date(year, 10, 1),
        new Date(year, 11, 1),
      ];

      //调接口获取
      this.holidayDate = this.getWeekdays(year);
      console.log(this.holidayDate);
      // 转化为对象数组
      const formattedDates = this.holidayDate.map((date) => {
        const dateObj = new Date(date);
        return {
          cal: dateObj,
          data: {
            day: date,
            isSelected: false,
            type: "current-month",
          },
        };
      });
      console.log(formattedDates);
      console.log("chushihua");
      this.clickedDates = formattedDates;

      this.$nextTick(() => {
        let holidayCell = document.getElementsByClassName("holiday-cell");
        for (let i in holidayCell) {
          if (undefined != holidayCell[i].style) {
            holidayCell[i].style.backgroundColor = "#FFFFFF";
          }
        }
        //给已选中的日期加背景色
        for (let i in this.holidayDate) {
          const month = parseInt(this.holidayDate[i].split("-")[1]) - 1;
          let span = document.getElementById(month + "-" + this.holidayDate[i]);
          span.style.backgroundColor = "#F56C6C";
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      let year = this.queryParams.holidayYear.getFullYear();
      this.initCalendar(year);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.holidayYear = new Date();
      this.handleQuery();
    },

    // 获取日期单元格的背景颜色
    getCellBackgroundColor(cal, data) {
      console.log("获取日期单元格的背景颜色");
      const clickedDate = this.clickedDates.find((clickedDate) => {
        return (
          clickedDate.cal.getFullYear() === cal.getFullYear() &&
          clickedDate.cal.getMonth() === cal.getMonth() &&
          clickedDate.data.day === data.day
        );
      });

      return clickedDate ? "#F56C6C" : "#FFFFFF";
    },

    // 点击日期单元格的事件
    selectCalendarDate(cal, data) {
      const clickedDateIndex = this.clickedDates.findIndex((clickedDate) => {
        console.log(clickedDate);

        return (
          clickedDate.cal.getFullYear() === cal.getFullYear() &&
          clickedDate.cal.getMonth() === cal.getMonth() &&
          clickedDate.data.day === data.day
        );
      });
      if (clickedDateIndex !== -1) {
        // 如果日期已经被点击过,移除记录并取消背景色
        this.clickedDates.splice(clickedDateIndex, 1);
      } else {
        // 否则,记录点击的日期
        this.clickedDates.push({ cal, data });
      }
      console.log(this.clickedDates);
    },
    // 提交按钮点击事件
    submitClickedDates() {
      const formattedDates = this.clickedDates.map((clickedDate) => {
        const date = clickedDate.data.day;
        const formattedDate = `${clickedDate.cal.getFullYear()}-${
          date.split("-")[1]
        }-${date.split("-")[2]}`;
        return formattedDate;
      });

      // 在这里处理格式化后的日期数组
      console.log("Formatted Dates:", formattedDates);

      // let dates = ['2025-01-01', '2025-01-06', '2025-01-07', '2025-01-08', '2025-01-10'];

      // 将日期字符串转换为 Date 对象
      // let dateObjects = dates.map(dateString => new Date(dateString));

      // // 按照 Date 对象进行排序
      // dateObjects.sort((a, b) => a - b);

      // // 将排序后的 Date 对象转换回日期字符串
      // let sortedDates = dateObjects.map(date => date.toISOString().split('T')[0]);

      // console.log(sortedDates);
    },
  },
};
</script>

<style>
.holiday .el-calendar__button-group {
  display: none;
}

.select-month .el-calendar__button-group {
  display: none;
}

.holiday .el-calendar-day {
  padding: 1px;
  width: 100%;
  height: 34px;
}

.select-month .el-calendar-day {
  padding: 1px;
  width: 100%;
}

.holiday-cell {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
相关推荐
滚雪球~12 分钟前
npm error code ETIMEDOUT
前端·npm·node.js
沙漏无语14 分钟前
npm : 无法加载文件 D:\Nodejs\node_global\npm.ps1,因为在此系统上禁止运行脚本
前端·npm·node.js
supermapsupport15 分钟前
iClient3D for Cesium在Vue中快速实现场景卷帘
前端·vue.js·3d·cesium·supermap
brrdg_sefg17 分钟前
WEB 漏洞 - 文件包含漏洞深度解析
前端·网络·安全
胡西风_foxww23 分钟前
【es6复习笔记】rest参数(7)
前端·笔记·es6·参数·rest
m0_7482548825 分钟前
vue+elementui实现下拉表格多选+搜索+分页+回显+全选2.0
前端·vue.js·elementui
星就前端叭1 小时前
【开源】一款基于Vue3 + WebRTC + Node + SRS + FFmpeg搭建的直播间项目
前端·后端·开源·webrtc
m0_748234521 小时前
前端Vue3字体优化三部曲(webFont、font-spider、spa-font-spider-webpack-plugin)
前端·webpack·node.js
Web阿成1 小时前
3.学习webpack配置 尝试打包ts文件
前端·学习·webpack·typescript
苹果醋32 小时前
Golang的文件加密工具
运维·vue.js·spring boot·nginx·课程设计