vue自定义日历组件(非UI组件)

<!---->
  <template>
       <ul>
        <li v-for="item in calendarArray" :key="item.time" >
          <div :style="'color:' + (item.isCurrentMonth ? '#000' : '#bbb')" >
            {{ item.day }}
          </div>
        </li>
      </ul>
  </template>
  <script>
  export default{
    data(){
      return {
       calendarArray: [
           {
            time: "2019-5-9",
            day: "9",
            isCurrentMonth:false,
            taskList: []
          }
        ],
      }
    },
  methods:{
    settingCalendarArray(date) {
         //date 传入标准格式日期 如:Tue Jun 01 2021 00:00:00 GMT+0800
        this.calendarArray = [];
        //判断当前年份是否是闰年(闰年2月份有29天,平年2月份只有28天)
        function isLeap(year) {
          return year % 4 == 0
            ? year % 100 != 0
              ? 1
              : year % 400 == 0
              ? 1
              : 0
            : 0;
        }
        var i,
          k,
          today = date ? date : new Date(), //获取当前日期
          y = today.getFullYear(), //获取日期中的年份
          m = today.getMonth(), //获取日期中的月份(需要注意的是:月份是从0开始计算,获取的值比正常月份的值少1)
          d = today.getDate(), //获取日期中的日(方便在建立日期表格时高亮显示当天)
          firstday = new Date(y, m, 1), //获取当月的第一天
          dayOfWeek = firstday.getDay(), //判断第一天是星期几(返回[0-6]中的一个,0代表星期天,1代表星期一,以此类推)
          days_per_month = new Array(
            31,
            28 + isLeap(y),
            31,
            30,
            31,
            30,
            31,
            31,
            30,
            31,
            30,
            31
          ), //创建月份数组
          cur_month_days = days_per_month[m], // 当前月的天数
          pre_month_days = days_per_month[m <= 0 ? 11 : m - 1], // 上个月天数
          next_month_days = days_per_month[m + 1 >= 11 ? 0 : m + 1], // 下个月天数
          str_nums = Math.ceil((dayOfWeek + cur_month_days) / 7); //确定日期表格所需的行数
          // str_nums * 7 --> 7表示每周7天,每行7列
        for (let i = 0; i < str_nums * 7; i++) {
          let time = "";
          let day = "";
          let currentMonth = false;  //定义每个格子的日期是否是当前月的日期
          if (i < dayOfWeek) { //   i值 小于 第一天是星期几-->表示是上月的日期 要显示灰色 currentMonth=false
            console.log(pre_month_days,dayOfWeek - 1,i,"888888888")
            // 当前月的第一天是 周三 即3
            day = pre_month_days - (dayOfWeek - 1 - i);
            time = (m <= 0 ? y - 1 : y) + "-" + m + "-" + day;
            console.log(time,"time")
          } else if (dayOfWeek + cur_month_days > i) {  //当前月或指定月的日期
            day = i - (dayOfWeek - 1);
            time = y + "-" + (m + 1) + "-" + day;
            currentMonth = true;
          } else { //下一个月的日期
            day = i - cur_month_days - (dayOfWeek - 1);
            time = (m >= 11 ? y + 1 : y) + "-" + (m + 2) + "-" + day;
          }
          this.calendarArray.push({
            time: time,
            day: day,
            isCurrentMonth: currentMonth
          });
        }
      },
    }
  }
  </script>

效果图:

posted @ 2021-07-16 13:40  Edith6  阅读(367)  评论(0编辑  收藏  举报