vue实现甘特图
Vue 实现甘特图的方法
使用开源库(推荐)
Vue-Ganttastic 是一个专为 Vue 设计的轻量级甘特图库,支持拖拽、缩放和自定义样式。安装后可直接嵌入组件:
npm install vue-ganttastic
示例代码:
<template>
<ganttastic :tasks="tasks" :options="options" />
</template>
<script>
import { Ganttastic } from 'vue-ganttastic';
export default {
components: { Ganttastic },
data() {
return {
tasks: [
{ id: 1, name: '任务A', start: '2023-01-01', end: '2023-01-05' },
{ id: 2, name: '任务B', start: '2023-01-06', end: '2023-01-10' }
],
options: {
viewMode: 'day',
style: {
'bar-color': '#4CAF50',
'bar-radius': '4px'
}
}
};
}
};
</script>
基于 D3.js 自定义实现
通过 D3.js 的灵活性构建高度定制化的甘特图:
npm install d3
核心逻辑示例:
<template>
<div ref="ganttContainer" class="gantt-chart"></div>
</template>
<script>
import * as d3 from 'd3';
export default {
mounted() {
this.renderGantt();
},
methods: {
renderGantt() {
const data = [
{ task: '开发', start: new Date(2023, 0, 1), end: new Date(2023, 0, 5) },
{ task: '测试', start: new Date(2023, 0, 6), end: new Date(2023, 0, 10) }
];
const svg = d3.select(this.$refs.ganttContainer)
.append('svg')
.attr('width', 800)
.attr('height', 300);
// 添加时间轴和任务条逻辑
// ...
}
}
};
</script>
<style>
.gantt-chart { width: 100%; border: 1px solid #eee; }
</style>
集成商业组件
Syncfusion 或 Bryntum 等商业库提供企业级功能:
- Syncfusion Vue Gantt:支持资源分配、关键路径分析
- Bryntum Gantt:包含基线比较、多项目管理
安装示例(Syncfusion):
npm install @syncfusion/ej2-vue-gantt
关键实现要点
- 时间计算:使用
moment.js或原生 Date 处理日期跨度 - 响应式设计:监听窗口变化动态调整 SVG 或 Canvas 尺寸
- 交互功能:通过 Vue 的
v-model实现任务数据双向绑定 - 性能优化:大数据量时采用虚拟滚动(如 vue-virtual-scroller)
样式定制技巧
- 通过 CSS 变量控制颜色主题
- 使用
transform: scale()实现时间轴缩放 - 添加
@click和@dblclick事件处理任务交互
选择方案时应评估项目需求,简单场景推荐 Vue-Ganttastic,复杂需求可考虑 D3.js 或商业组件。







