vue实现甘特图展示
使用Vue-Gantt组件库(如vue-gantt-elastic)
安装依赖包:
npm install vue-gantt-elastic
基础实现代码:
<template>
<gantt-elastic
:tasks="tasks"
:options="options"
@tasks-changed="handleTasksChange"
></gantt-elastic>
</template>
<script>
import GanttElastic from 'vue-gantt-elastic';
export default {
components: { GanttElastic },
data() {
return {
tasks: [
{
id: 'task1',
label: '项目启动',
start: '2023-01-01',
end: '2023-01-10',
progress: 50
}
],
options: {
title: {
label: '项目计划'
}
}
};
},
methods: {
handleTasksChange(updatedTasks) {
this.tasks = updatedTasks;
}
}
};
</script>
基于D3.js自定义实现
通过D3.js的缩放和拖拽功能构建交互式甘特图:
<template>
<div ref="ganttContainer" class="gantt-chart"></div>
</template>
<script>
import * as d3 from 'd3';
export default {
mounted() {
this.renderGantt();
},
data() {
return {
tasks: [
{ id: 1, name: '需求分析', start: new Date(2023, 0, 1), end: new Date(2023, 0, 5) }
]
};
},
methods: {
renderGantt() {
const svg = d3.select(this.$refs.ganttContainer)
.append('svg')
.attr('width', 800)
.attr('height', 400);
// 时间比例尺
const xScale = d3.scaleTime()
.domain([new Date(2023, 0, 1), new Date(2023, 0, 31)])
.range([0, 700]);
// 绘制任务条
svg.selectAll('.task')
.data(this.tasks)
.enter()
.append('rect')
.attr('class', 'task-bar')
.attr('x', d => xScale(d.start))
.attr('y', (d, i) => i * 30 + 20)
.attr('width', d => xScale(d.end) - xScale(d.start))
.attr('height', 20)
.attr('fill', '#4CAF50');
}
}
};
</script>
集成第三方甘特图库(如Frappe Gantt)
安装Frappe Gantt:
npm install frappe-gantt
Vue封装实现:
<template>
<div ref="gantt"></div>
</template>
<script>
import Gantt from 'frappe-gantt';
export default {
mounted() {
new Gantt(this.$refs.gantt, [
{
id: 't1',
name: '任务1',
start: '2023-01-01',
end: '2023-01-05',
progress: 30
}
], {
view_mode: 'Week'
});
}
};
</script>
响应式数据处理
动态更新甘特图数据示例:
watch: {
tasks: {
handler(newTasks) {
if (this.gantt) {
this.gantt.refresh(newTasks);
}
},
deep: true
}
}
样式优化建议
添加CSS增强可视化效果:
.gantt-chart {
font-family: Arial;
overflow-x: auto;
}
.task-bar:hover {
opacity: 0.8;
stroke: #333;
stroke-width: 1px;
}






