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: 1, name: '任务A', start: '2023-01-01', end: '2023-01-10' },
{ id: 2, name: '任务B', start: '2023-01-05', end: '2023-01-15' }
]
};
}
};
</script>
基于D3.js自定义甘特图
通过D3.js实现高度自定义的甘特图,适合需要复杂交互或独特设计的场景。结合Vue的生命周期管理数据与DOM操作。
<template>
<div ref="ganttContainer"></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, 20) }
];
const svg = d3.select(this.$refs.ganttContainer)
.append('svg')
.attr('width', 800)
.attr('height', 300);
// 添加D3绘图逻辑(示例简化)
}
}
};
</script>
集成第三方库Vue-Gantt-Easy
Vue-Gantt-Easy提供丰富的API和主题定制,支持时间轴缩放、任务依赖关系等高级功能。
npm install vue-gantt-easy
<template>
<vue-gantt-easy :data="ganttData" />
</template>
<script>
import VueGanttEasy from 'vue-gantt-easy';
export default {
components: { VueGanttEasy },
data() {
return {
ganttData: {
tasks: [
{ id: 1, text: '设计', start_date: '2023-01-01', duration: 5 },
{ id: 2, text: '开发', start_date: '2023-01-06', duration: 10 }
]
}
};
}
};
</script>
使用AntV G2Plot的Vue封装
蚂蚁金服的G2Plot提供专业级可视化方案,通过Vue封装调用其甘特图模块,适合数据密集型场景。
npm install @antv/g2plot
<template>
<div ref="chart"></div>
</template>
<script>
import { Gantt } from '@antv/g2plot';
export default {
mounted() {
const data = [
{ start: '2023-01-01', end: '2023-01-10', name: '需求分析' }
];
const plot = new Gantt(this.$refs.chart, {
data,
height: 400,
xField: 'start',
yField: 'name',
xAxis: { type: 'time' }
});
plot.render();
}
};
</script>
样式优化技巧
- 主题色配置:通过CSS变量或库提供的theme属性统一调整颜色。
- 响应式布局:监听窗口大小变化,动态调整甘特图容器的宽度和缩放比例。
- 动画效果:为任务条添加过渡动画,提升用户体验。
.gantt-bar {
transition: width 0.3s ease;
}
以上方案可根据项目需求选择,轻量级场景推荐Vue-Ganttastic,复杂需求建议结合D3.js或AntV实现。






