甘特图vue实现
甘特图在 Vue 中的实现方法
使用现成库(推荐)
推荐使用 vue-ganttastic 或 dhtmlx-gantt 等现成库快速实现甘特图功能。
安装 vue-ganttastic:
npm install vue-ganttastic
基础示例代码:
<template>
<GanttChart
:tasks="tasks"
:options="options"
/>
</template>
<script>
import { GanttChart } from 'vue-ganttastic'
export default {
components: { GanttChart },
data() {
return {
tasks: [
{ id: 1, name: 'Task 1', start: '2023-01-01', end: '2023-01-05' },
{ id: 2, name: 'Task 2', start: '2023-01-06', end: '2023-01-10' }
],
options: {
viewMode: 'day',
style: {
'font-size': '12px'
}
}
}
}
}
</script>
自定义实现方案
如果需要高度定制化,可以使用 SVG 或 Canvas 自行绘制甘特图。
基础结构示例:
<template>
<div class="gantt-container">
<div class="gantt-header">
<!-- 时间轴标题 -->
</div>
<div class="gantt-body">
<!-- 任务行 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
tasks: [],
timeline: []
}
},
methods: {
calculatePositions() {
// 计算每个任务的位置和宽度
},
renderTasks() {
// 渲染任务条
}
}
}
</script>
<style>
.gantt-container {
width: 100%;
overflow-x: auto;
}
</style>
关键功能实现要点
时间轴计算
// 计算日期跨度
const dateDiff = (start, end) => {
return (new Date(end) - new Date(start)) / (1000 * 60 * 60 * 24)
}
任务条定位
// 计算任务条位置和宽度
const calculateTaskStyle = (task) => {
const startOffset = dateDiff(projectStart, task.start)
const duration = dateDiff(task.start, task.end)
return {
left: `${startOffset * columnWidth}px`,
width: `${duration * columnWidth}px`
}
}
交互功能实现
拖拽调整任务时间
// 使用 vue-draggable 或原生拖拽API
mounted() {
this.$el.querySelectorAll('.task-bar').forEach(bar => {
bar.addEventListener('mousedown', this.startDrag)
})
}
样式优化建议
响应式布局
@media (max-width: 768px) {
.gantt-header {
font-size: 10px;
}
}
动画效果
.task-bar {
transition: all 0.3s ease;
}
注意事项
- 处理大量数据时考虑虚拟滚动
- 时区问题需要特别注意
- 项目时间跨度过大时需要动态缩放
- 复杂依赖关系可能需要额外库支持
以上方案可根据实际需求选择使用现成库或自定义开发,现成库适合快速实现基本功能,自定义开发则更适合特殊需求场景。







