vue3甘特图
时间: 2025-05-07 21:08:21 浏览: 33
### 如何在 Vue3 中实现甘特图
#### 使用 DHTMLX Gantt 图表
DHTMLX Gantt 提供了一个成熟的解决方案,适用于需要复杂任务管理和时间跟踪的场景。以下是集成方法:
1. **安装依赖**
需要通过 npm 或 yarn 安装 `dhtmlx-gantt` 的相关库。
```bash
npm install dhtmlx-gantt
```
2. **初始化配置**
在 Vue 3 组件中引入并初始化 Gantt 图表。
```javascript
import { onMounted } from 'vue';
import gantt from 'dhtmlx-gantt';
export default {
name: 'GanttChart',
setup() {
let ganttContainer;
onMounted(() => {
gantt.init(ganttContainer);
gantt.parse({
data: [
{ id: 1, text: "Task #1", start_date: "01-04-2023", duration: 3 },
{ id: 2, text: "Task #2", start_date: "02-04-2023", duration: 5 }
]
});
});
return { ganttContainer };
}
};
```
上述代码展示了如何加载数据到 Gantt 图表中[^1]。
---
#### 使用 vue-gantt-schedule-timeline-calendar 插件
另一个流行的选项是使用社区插件 `vue-gantt-schedule-timeline-calendar` 来快速搭建基础功能。
1. **安装依赖**
同样可以通过 npm 进行安装:
```bash
npm install vue-gantt-schedule-timeline-calendar
```
2. **基本用法**
下面是一个简单的示例展示其核心功能:
```javascript
import { defineComponent } from 'vue';
import GanttScheduleTimelineCalendar from 'vue-gantt-schedule-timeline-calendar';
export default defineComponent({
components: { GanttScheduleTimelineCalendar },
data() {
return {
items: [
{ id: 1, title: 'Task A', startDate: new Date(2023, 3, 1), endDate: new Date(2023, 3, 5) },
{ id: 2, title: 'Task B', startDate: new Date(2023, 3, 6), endDate: new Date(2023, 3, 8) }
],
};
},
});
```
此外,还可以利用 ItemMovement 插件增强交互体验[^3]。
---
#### 自定义封装简易版甘特图
如果现有插件无法完全满足需求,也可以尝试手动封装一个轻量级版本。以下是一种基于 ECharts 的实现方式:
1. **安装 ECharts**
```bash
npm install echarts
```
2. **创建图表逻辑**
利用瀑布图模拟甘特图的时间轴布局。
```javascript
import * as echarts from 'echarts';
const initEchartsGantt = (containerId, tasks) => {
const chartDom = document.getElementById(containerId);
const myChart = echarts.init(chartDom);
const option = {
tooltip: {},
xAxis: {
type: 'time'
},
yAxis: {
data: tasks.map(task => task.name),
},
series: [{
type: 'bar',
stack: 'total',
encode: {
x: ['start', 'end'],
y: 'name'
},
data: tasks,
}]
};
myChart.setOption(option);
};
// 调用函数传入容器 ID 和任务列表
initEchartsGantt('gantt-container', [
{ name: 'Task 1', start: '2023-04-01', end: '2023-04-03' },
{ name: 'Task 2', start: '2023-04-04', end: '2023-04-07' }
]);
```
尽管这种方法较为原始,但它允许高度定制化[^4]。
---
#### 总结
以上介绍了三种不同的方案:借助成熟框架(如 DHTMLX)、采用社区插件以及自定义开发。每种方法各有优劣,具体选择取决于项目的实际需求和技术栈偏好。
阅读全文
相关推荐



















