You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3+TypeScript+FullCalendar V6:按用户查看年月动态获取事件

实现FullCalendar V6动态加载指定年月的事件

在Vue3+TypeScript环境下,FullCalendar的events属性支持传入异步函数,这个函数会在日历切换视图(比如点击上月/下月按钮)时自动触发,你可以通过函数参数获取当前视图的日期范围,从中提取年月来构建参数化请求,具体实现如下:

核心思路

FullCalendar调用events函数时,会传入一个包含当前视图日期信息的info对象,其中info.start和info.end是当前视图的起始/结束日期。你可以从这两个日期中解析出当前要加载的年月,然后请求后端接口获取对应数据。

具体实现步骤

1. 编写带参数的事件请求函数

先封装一个异步请求函数,接收year和month作为参数,请求后端接口返回对应年月的日历事件:

// 假设你的后端接口是 /api/calendar/events
async function fetchCalendarEvents(year: number, month: number) {
  const response = await fetch(`/api/calendar/events?year=${year}&month=${month}`);
  const events = await response.json();
  // 确保返回的事件符合FullCalendar要求的格式,比如包含title、start等字段
  return events;
}

2. 配置calendarOptions的events属性

将events设为一个异步函数,从info参数中提取年月,调用上面的请求函数:

<template>
  <FullCalendar :options="calendarOptions" />
</template>

<script setup lang="ts">
import FullCalendar from '@fullcalendar/vue3';
import dayGridPlugin from '@fullcalendar/daygrid';

const calendarOptions = {
  plugins: [dayGridPlugin],
  initialView: 'dayGridMonth',
  // 核心:用异步函数动态加载事件
  events: async function(info) {
    // 从start日期中提取年份和月份(注意JS的getMonth是0-based,要+1转成1-12)
    const year = info.start.getFullYear();
    const month = info.start.getMonth() + 1;
    // 调用请求函数获取对应年月的事件
    return await fetchCalendarEvents(year, month);
  },
  // 可选:添加年月切换的回调,方便调试或额外处理
  dateSet: function(info) {
    console.log('当前视图年月:', info.view.currentStart.getFullYear(), info.view.currentStart.getMonth() + 1);
  }
};
</script>

关键细节说明

  • 日期解析:info.start是当前视图的第一个日期(比如当月1号),用getFullYear()拿年份,getMonth()+1转成实际月份(因为JS Date的月份是0开始的)。
  • 后端接口要求:后端需要接收year和month参数,返回符合FullCalendar事件格式的数据,示例格式:
    [
      { "title": "会议", "start": "2024-05-10" },
      { "title": "团建", "start": "2024-05-15", "end": "2024-05-16" }
    ]
    
  • 加载状态:FullCalendar会自动处理加载状态,请求期间日历会显示加载动画,无需额外处理。

额外优化

如果需要手动触发事件刷新(比如新增/删除事件后),可以通过日历实例调用refetchEvents()方法:

import { ref } from 'vue';

const calendarRef = ref<InstanceType<typeof FullCalendar>>();

// 手动刷新事件
function refreshEvents() {
  calendarRef.value?.getApi().refetchEvents();
}

然后在模板中给FullCalendar添加ref:

<FullCalendar ref="calendarRef" :options="calendarOptions" />

内容的提问来源于stack exchange,提问作者Reason

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 04:01:44