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

FullCalendar拖拽添加数据时API调用时机捕获问题求助

问题分析与解决方案

核心问题

你的代码同时混用了原生拖拽事件绑定和FullCalendar官方Draggable组件,导致事件逻辑冲突,自定义的handleDrop无法正常触发。另外,你试图通过原生DOM事件获取日历资源信息的方式也不正确,应该利用FullCalendar提供的回调参数来获取数据。

修复步骤

1. 移除冗余的原生拖拽事件绑定

  • 模板中删除<tr>标签上的@dragstart和@drop属性,只保留draggable="true":
<tr
  class="fc-event"
  v-for="(bomData, index) in getBomData"
  :key="index"
  draggable="true"
>
  • 删除自定义的handleDragStart方法,拖拽数据的管理交给FullCalendar的Draggable组件处理。

2. 改用FullCalendar官方的drop回调

修改calendarOptions配置,添加官方的drop回调(这才是拖拽元素到日历后触发的正确时机):

calendarOptions: {
  // ... 其他原有配置
  droppable: true,
  // 添加官方drop回调
  drop: async (info) => {
    // 从拖拽数据中获取bom信息
    const bomData = info.event.extendedProps.bomData;
    // 获取放置目标的设备资源
    const targetFacility = info.resource;
    
    // 构造日历事件对象
    const newEvent = {
      id: Date.now(),
      title: `${bomData.product_unit} - ${bomData.process} - ${this.getProductAmount}`,
      start: info.date,
      allDay: true,
      resourceId: targetFacility.id
    };
    this.calendarEvents.push(newEvent);
    
    // 调用API保存数据
    const payload = {
      title: newEvent.title,
      start: info.date,
      end_date: info.date,
      facility_name: targetFacility.title
    };
    await this.$store.dispatch('postBom', payload);
  },
  // ... 其他原有配置
}

3. 简化initializeDraggable方法

只保留FullCalendar Draggable的初始化逻辑,移除冗余的事件绑定:

initializeDraggable() {
  const containerEl = document.getElementById('external-events');
  if (containerEl) {
    const eventElements = containerEl.getElementsByClassName('fc-event');
    Array.from(eventElements).forEach((eventEl, index) => {
      if (eventEl.classList.contains('draggable-initialized')) return;
      
      new Draggable(eventEl, {
        eventData: () => {
          const bomData = this.bomDatas[index];
          return {
            title: `${bomData.product_unit} - ${bomData.process} - ${this.getProductAmount}`,
            // 将bom数据附加到事件的扩展属性中,方便drop回调获取
            extendedProps: { bomData }
          };
        }
      });
      
      eventEl.classList.add('draggable-initialized');
    });
  }
}

4. 移除多余的事件绑定

删除initializeDraggable方法中对calendar-container的drop和dragover事件绑定,FullCalendar的droppable: true配置会自动处理这些基础事件逻辑。

关键注意事项

  • 优先使用FullCalendar官方提供的回调和API,避免混合原生拖拽事件,防止逻辑冲突。
  • FullCalendar的drop回调参数info包含了所有需要的信息:放置日期、目标资源、拖拽的事件数据等,无需通过原生DOM方式获取。
  • 确保calendarEvents数组是响应式的,添加新事件后日历会自动更新视图。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:37:03