vue实现甘特图
使用 vue-ganttastic 库实现甘特图
vue-ganttastic 是一个轻量级的 Vue 甘特图组件库,支持任务拖拽、缩放和自定义样式。
安装依赖:
npm install vue-ganttastic
基础实现代码:

<template>
<GanttChart :tasks="tasks" />
</template>
<script>
import { GanttChart } from 'vue-ganttastic'
export default {
components: { GanttChart },
data() {
return {
tasks: [
{
id: 'task1',
name: '任务一',
start: '2023-01-01',
end: '2023-01-05',
progress: 50
},
{
id: 'task2',
name: '任务二',
start: '2023-01-03',
end: '2023-01-08',
progress: 20
}
]
}
}
}
</script>
使用 dhtmlx-gantt 实现专业级甘特图
dhtmlx-gantt 是功能强大的商业甘特图库,提供 Vue 封装版本。
安装依赖:

npm install dhtmlx-gantt
基础实现代码:
<template>
<div ref="gantt_container" style="width:100%; height:400px;"></div>
</template>
<script>
import { gantt } from 'dhtmlx-gantt'
import 'dhtmlx-gantt/codebase/dhtmlxgantt.css'
export default {
mounted() {
gantt.init(this.$refs.gantt_container)
gantt.parse({
data: [
{ id: 1, text: "任务一", start_date: "2023-01-01", duration: 5 },
{ id: 2, text: "任务二", start_date: "2023-01-03", duration: 4 }
],
links: [
{ id: 1, source: 1, target: 2, type: "0" }
]
})
}
}
</script>
自定义实现简单甘特图
对于简单需求,可以使用纯 Vue 实现基础甘特图功能。
实现代码示例:
<template>
<div class="gantt-container">
<div v-for="task in tasks" :key="task.id" class="gantt-task"
:style="taskStyle(task)">
{{ task.name }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
tasks: [
{ id: 1, name: '任务A', start: 0, duration: 3 },
{ id: 2, name: '任务B', start: 2, duration: 4 }
],
dayWidth: 50
}
},
methods: {
taskStyle(task) {
return {
width: `${task.duration * this.dayWidth}px`,
left: `${task.start * this.dayWidth}px`,
backgroundColor: `hsl(${task.id * 60}, 70%, 80%)`
}
}
}
}
</script>
<style>
.gantt-container {
position: relative;
height: 300px;
border: 1px solid #ddd;
}
.gantt-task {
position: absolute;
height: 30px;
line-height: 30px;
padding: 0 10px;
border-radius: 3px;
margin-top: 5px;
}
</style>
甘特图功能扩展建议
- 时间轴控制:添加缩放按钮调整时间粒度(天/周/月)
- 任务交互:实现拖拽调整任务时间、右键菜单操作
- 进度显示:在任务条上叠加进度指示条
- 依赖关系:用箭头线显示任务间的依赖关系
- 资源分配:添加人员/资源分配显示功能
性能优化方案
- 虚拟滚动:只渲染可视区域内的任务项
- 数据分页:对大规模数据采用分页加载
- 防抖处理:对频繁操作如拖拽进行防抖优化
- Web Worker:将复杂计算移入 Web Worker






