vue创建一个日历组件

首先,在Vue项目中创建一个日历组件所需要的Vue单文件组件(.vue文件)。

在template标签中,可以使用table和tr标签来创建一个简单的日历表格,使用v-for指令来循环渲染每一行日期。

在script标签中:

  1. 使用moment.js库来处理日期时间,这个库非常方便,可以安装moment.js并引入。
  2. 设置当前月份和年份以及当前日期,使用计算属性computed来根据当前月份和年份计算出日历中的日期和周几。
  3. 在methods中,封装一个方法handlePrevMonth和handleNextMonth来控制上一个月和下一个月的切换。

最后,在style标签中,可以设置样式来美化日历组件。

这样,就可以创建一个基本的Vue日历组件了。具体实现可以看下面的代码:

vue 复制代码
<template>
  <div class="calendar">
    <table>
      <thead>
        <tr>
          <th colspan="7">{{ currentMonth }} {{ currentYear }}</th>
        </tr>
        <tr>
          <th v-for="day in days">{{ day }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="week in weeks" :key="week">
          <td v-for="day in week" :class="{ 'today': isToday(day), 'different-month': !isCurrentMonth(day) }">{{ day.format('D') }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import moment from 'moment';

export default {
  name: 'Calendar',
  data() {
    return {
      currentDate: moment(),
    };
  },
  computed: {
    currentMonth() {
      return this.currentDate.format('MMMM');
    },
    currentYear() {
      return this.currentDate.format('YYYY');
    },
    days() {
      return ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    },
    weeks() {
      const weeks = [];
      const date = this.currentDate.clone().startOf('month').startOf('week');
      do {
        const week = [];
        for (let i = 0; i < 7; i++) {
          week.push(date.clone());
          date.add(1, 'day');
        }
        weeks.push(week);
      } while (date.month() === this.currentDate.month());
      return weeks;
    },
  },
  methods: {
    isToday(date) {
      return moment().isSame(moment(date), 'day');
    },
    isCurrentMonth(date) {
      return moment(date).isSame(this.currentDate, 'month');
    },
    handlePrevMonth() {
      this.currentDate.subtract(1, 'month');
    },
    handleNextMonth() {
      this.currentDate.add(1, 'month');
    },
  },
};
</script>

<style scoped>
.calendar {
  margin: 20px;
}

table {
  border-collapse: collapse;
  width: 100%;
  max-width: 600px;
}

th,
td {
  text-align: center;
  padding: 10px;
  border: 1px solid #ddd;
}

.weekend {
  color: red;
}

.today {
  background-color: #f5f5f5;
}

.different-month {
  color: #ddd;
}
</style>

然后在页面中引入Calendar组件即可。

相关推荐
小村儿19 分钟前
连载06 - Hooks 源码深度解析:Claude Code 的确定性自动化体系
前端·后端·ai编程
心中无石马29 分钟前
uniapp引入tailwindcss4.x
前端·css·uni-app
焰火19991 小时前
[Vue]可重置的响应式状态reactive
前端·vue.js
陆枫Larry1 小时前
CSS transform scale:图片放大效果背后的原理
前端
源码宝1 小时前
基于 SpringBoot + Vue 的医院随访系统:技术架构与功能实现
java·vue.js·spring boot·架构·源码·随访系统·随访管理
昇腾CANN1 小时前
TileLang-Ascend 算子性能优化方法与实操
开发语言·javascript·性能优化·昇腾·cann
老王以为1 小时前
为什么 React 和 Vue 不一样?
前端·vue.js·react.js
web打印社区1 小时前
2026最新Web静默打印解决方案,无插件无预览,完美替代Lodop
前端·javascript·vue.js·electron·pdf
这个DBA有点耶1 小时前
分组排名不用窗口函数?那你还在写几十行的子查询
前端·代码规范
ZhiqianXia1 小时前
《The Design of Design》阅读笔记
前端·笔记·microsoft