纯vue项目实现甘特图
使用第三方库(如vue-gantt-elastic)
安装依赖库vue-gantt-elastic,该库专为Vue设计,支持拖拽、缩放、自定义样式等功能。
npm install vue-gantt-elastic
在组件中引入并配置数据:
<template>
<gantt-elastic
:tasks="tasks"
:options="options"
@tasks-changed="updateTasks"
></gantt-elastic>
</template>
<script>
import GanttElastic from "vue-gantt-elastic";
export default {
components: { GanttElastic },
data() {
return {
tasks: [
{ id: 1, text: "Task 1", start: "2023-01-10", duration: 5 },
{ id: 2, text: "Task 2", start: "2023-01-15", duration: 3 }
],
options: {
title: { label: "Project Timeline" }
}
};
},
methods: {
updateTasks(updatedTasks) {
this.tasks = updatedTasks;
}
}
};
</script>
基于原生SVG手动实现
通过SVG绘制甘特图,结合Vue的数据绑定实现动态更新。
定义任务数据结构和计算坐标的逻辑:
data() {
return {
tasks: [
{ id: 1, name: "Design", start: new Date(2023, 0, 1), end: new Date(2023, 0, 10) },
{ id: 2, name: "Development", start: new Date(2023, 0, 5), end: new Date(2023, 0, 20) }
],
scale: 20 // 像素/天
};
},
computed: {
svgPaths() {
return this.tasks.map(task => {
const x1 = (task.start - new Date(2023, 0, 1)) / (1000 * 60 * 60 * 24) * this.scale;
const width = (task.end - task.start) / (1000 * 60 * 60 * 24) * this.scale;
return { x1, width, task };
});
}
}
模板中使用v-for渲染SVG元素:
<svg width="800" height="400">
<g v-for="(path, index) in svgPaths" :key="index">
<rect
:x="path.x1"
y="20"
:width="path.width"
height="30"
fill="#4CAF50"
@click="selectTask(path.task)"
/>
<text :x="path.x1" y="50">{{ path.task.name }}</text>
</g>
</svg>
集成FullCalendar与Gantt插件
FullCalendar的resource-timeline视图可模拟甘特图功能。
安装依赖并配置时间轴视图:
npm install @fullcalendar/vue @fullcalendar/resource-timeline
组件实现示例:
<template>
<FullCalendar :options="calendarOptions" />
</template>
<script>
import FullCalendar from "@fullcalendar/vue";
import resourceTimelinePlugin from "@fullcalendar/resource-timeline";
export default {
components: { FullCalendar },
data() {
return {
calendarOptions: {
plugins: [resourceTimelinePlugin],
initialView: "resourceTimelineWeek",
resources: [
{ id: "1", title: "Task A" },
{ id: "2", title: "Task B" }
],
events: [
{ resourceId: "1", start: "2023-01-01", end: "2023-01-10", title: "Design" },
{ resourceId: "2", start: "2023-01-05", end: "2023-01-15", title: "Develop" }
]
}
};
}
};
</script>
注意事项
- 时间格式处理:确保日期数据使用ISO格式或JavaScript的
Date对象,避免时区问题。 - 响应式设计:通过监听窗口大小变化动态调整SVG或Canvas的尺寸。
- 性能优化:大数据量时考虑虚拟滚动(如使用
vue-virtual-scroller)。
以上方法可根据项目复杂度选择,第三方库适合快速实现,原生方案适合高度定制需求。







