vue制作简易日历

发布时间:2023年12月20日

你可以使用Vue.js来制作一个简易日历。:

<!DOCTYPE html>
<html>
<head>
  <title>Vue简易日历</title>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <style>
    table {
      border-collapse: collapse;
    }
    td {
      border: 1px solid black;
      padding: 5px;
    }
    th {
      background-color: lightgray;
      border: 1px solid black;
      padding: 5px;
    }
  </style>
</head>
<body>
  <div id="app">
    <h1>简易日历</h1>
    <table>
      <thead>
        <tr>
          <th v-for="day in daysOfWeek">{{ day }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="week in calendar">
          <td v-for="day in week">{{ day }}</td>
        </tr>
      </tbody>
    </table>
  </div>

  <script>
    new Vue({
      el: '#app',
      data: {
        daysOfWeek: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
        calendar: [],
      },
      created() {
        this.generateCalendar();
      },
      methods: {
        generateCalendar() {
          const today = new Date();
          const year = today.getFullYear();
          const month = today.getMonth();

          const firstDayOfMonth = new Date(year, month, 1);
          const lastDayOfMonth = new Date(year, month + 1, 0);

          const firstDayOfWeek = firstDayOfMonth.getDay();
          const lastDayOfWeek = lastDayOfMonth.getDay();

          const daysInMonth = lastDayOfMonth.getDate();

          const calendar = [[]];
          let weekIndex = 0;

          for (let i = 0; i < firstDayOfWeek; i++) {
            calendar[weekIndex].push('');
          }

          for (let day = 1; day <= daysInMonth; day++) {
            if (calendar[weekIndex].length === 7) {
              calendar.push([]);
              weekIndex++;
            }
            calendar[weekIndex].push(day);
          }

          for (let i = lastDayOfWeek + 1; i < 7; i++) {
            calendar[weekIndex].push('');
          }

          this.calendar = calendar;
        },
      }
    });
  </script>
</body>
</html>

你可以将此代码保存到一个HTML文件中,并在浏览器中打开查看结果。该日历将显示当前月份的日历表格。

文章来源:https://blog.csdn.net/weixin_59525879/article/details/135039077
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。