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组件即可。

相关推荐
Hi_kenyon1 小时前
VUE3套用组件库快速开发(以Element Plus为例)二
开发语言·前端·javascript·vue.js
Irene19911 小时前
Vue 3 响应式系统类型关系总结(附:computed、props)
vue.js·props·响应式类型
起名时在学Aiifox1 小时前
Vue 3 响应式缓存策略:从页面状态追踪到智能数据管理
前端·vue.js·缓存
天若有情6731 小时前
校园二手交易系统实战开发全记录(vue+SpringBoot+MySQL)
vue.js·spring boot·mysql
计算机程序设计小李同学2 小时前
个人数据管理系统
java·vue.js·spring boot·后端·web安全
李剑一2 小时前
uni-app实现本地MQTT连接
前端·trae
EndingCoder2 小时前
Any、Unknown 和 Void:特殊类型的用法
前端·javascript·typescript
oden2 小时前
代码高亮、数学公式、流程图... Astro 博客进阶全指南
前端
GIS之路2 小时前
GDAL 实现空间分析
前端