Creating a Gantt chart component in Vue.js 3 using the Options API is a substantial project, especially when incorporating features like drag-and-drop, resizing, task dependencies, a task hierarchy tree, and resource assignments. Below is a step-by-step guide to help you build such a component.
Table of Contents
- Component Setup
- Task Data Structure
- Task Hierarchy Tree
- Gantt Chart Rendering
- Drag and Resize Functionality
- Task Dependencies
- Resource Assignment Display
- Styling
- Performance Optimization
- Considerations and Libraries
1. Component Setup
Create a new Vue component named GanttChart.vue.
<template>
<div class="gantt-chart">
<div class="task-tree">
<!-- Task hierarchy rendered here -->
</div>
<div class="chart-area">
<!-- Gantt chart bars rendered here -->
</div>
</div>
</template>
<script>
export default {
name: 'GanttChart',
props: {
tasks: {
type: Array,
required: true,
},
},
data() {
return {
// Reactive data properties
};
},
methods: {
// Methods for drag, resize, and other interactions
},
};
</script>
<style scoped>
/* Styles go here */
</style>
2. Task Data Structure
Define a consistent structure for your tasks to ensure they can be rendered correctly.
// Example task structure
[
{
id: 1,
name: 'Project Initiation',
startDate: '2023-11-01',
endDate: '2023-11-05',
dependencies: [],
resource: 'Project Manager',
children: [
{
id: 2,
name: 'Requirement Gathering',
startDate: '2023-11-02',
endDate: '2023-11-04',
dependencies: [1],
resource: 'Business Analyst',
children: [],
},
// More subtasks
],
},
// More tasks
];
Each task may include:
id: Unique identifier.
name: Task name.
startDate and endDate: Task duration.
dependencies: Array of task IDs this task depends on.
resource: Assigned resource (person or team).
children: Array of subtasks.
3. Task Hierarchy Tree
Render the task hierarchy on the left side of the Gantt chart.
<!-- In the template -->
<div class="task-tree">
<ul>
<task-item
v-for="task in tasks"
:key="task.id"
:task="task"
></task-item>
</ul>
</div>
Create a recursive component TaskItem for tasks and subtasks.
<!-- TaskItem.vue -->
<template>
<li>
<div class="task-info">
<span class="task-name">{{ task.name }}</span>
<!-- Display assigned resource -->
<span class="task-resource">{{ task.resource }}</span>
</div>
<ul v-if="task.children && task.children.length">
<task-item
v-for="child in task.children"
:key="child.id"
:task="child"
></task-item>
</ul>
</li>
</template>
<script>
export default {
name: 'TaskItem',
props: {
task: {
type: Object,
required: true,
},
},
};
</script>
<style scoped>
/* Styles for task tree */
</style>
4. Gantt Chart Rendering
Render tasks as bars corresponding to their start and end dates.
Calculate Date Ranges
// In data()
return {
chartStartDate: '2023-11-01',
chartEndDate: '2023-12-31',
};
Helper Methods
methods: {
// Calculate total days in chart
getTotalChartDays() {
return this.getDurationInDays(this.chartStartDate, this.chartEndDate);
},
// Calculate duration between two dates
getDurationInDays(start, end) {
const startDate = new Date(start);
const endDate = new Date(end);
const timeDiff = endDate - startDate;
return Math.ceil(timeDiff / (1000 * 3600 * 24));
},
// Calculate position and width for a task bar
getTaskBarStyle(task) {
const totalDays = this.getTotalChartDays();
const taskStartOffset = this.getDurationInDays(this.chartStartDate, task.startDate);
const taskDuration = this.getDurationInDays(task.startDate, task.endDate);
const leftPercent = (taskStartOffset / totalDays) * 100;
const widthPercent = (taskDuration / totalDays) * 100;
return {
left: `${leftPercent}%`,
width: `${widthPercent}%`,
};
},
},
Render Bars
<!-- In the template -->
<div class="chart-area">
<div class="chart-bars">
<task-bar
v-for="task in flatTasks"
:key="task.id"
:task="task"
:style="getTaskBarStyle(task)"
@mousedown.left="startDrag(task, $event)"
@mousedown.right="startResize(task, $event)"
></task-bar>
</div>
</div>
flatTasks is a computed property that flattens the task hierarchy for rendering.
5. Drag and Resize Functionality
Implement drag-and-drop and resizing to adjust task schedules interactively.
Data Properties
data() {
return {
activeTask: null,
actionType: null, // 'drag' or 'resize'
initialMouseX: 0,
initialTaskStart: null,
initialTaskEnd: null,
};
},
Methods
methods: {
startDrag(task, event) {
this.activeTask = task;
this.actionType = 'drag';
this.initialMouseX = event.clientX;
this.initialTaskStart = new Date(task.startDate);
this.initialTaskEnd = new Date(task.endDate);
document.addEventListener('mousemove', this.onMouseMove);
document.addEventListener('mouseup', this.onMouseUp);
},
startResize(task, event) {
this.activeTask = task;
this.actionType = 'resize';
this.initialMouseX = event.clientX;
this.initialTaskEnd = new Date(task.endDate);
document.addEventListener('mousemove', this.onMouseMove);
document.addEventListener('mouseup', this.onMouseUp);
},
onMouseMove(event) {
if (!this.activeTask) return;
const deltaX = event.clientX - this.initialMouseX;
const daysShifted = this.pixelsToDays(deltaX);
if (this.actionType === 'drag') {
const newStartDate = new Date(this.initialTaskStart);
const newEndDate = new Date(this.initialTaskEnd);
newStartDate.setDate(newStartDate.getDate() + daysShifted);
newEndDate.setDate(newEndDate.getDate() + daysShifted);
this.$set(this.activeTask, 'startDate', this.formatDate(newStartDate));
this.$set(this.activeTask, 'endDate', this.formatDate(newEndDate));
} else if (this.actionType === 'resize') {
const newEndDate = new Date(this.initialTaskEnd);
newEndDate.setDate(newEndDate.getDate() + daysShifted);
if (newEndDate > new Date(this.activeTask.startDate)) {
this.$set(this.activeTask, 'endDate', this.formatDate(newEndDate));
}
}
},
onMouseUp() {
this.activeTask = null;
this.actionType = null;
document.removeEventListener('mousemove', this.onMouseMove);
document.removeEventListener('mouseup', this.onMouseUp);
},
pixelsToDays(pixels) {
const chartWidth = this.$refs.chartArea.offsetWidth;
const totalDays = this.getTotalChartDays();
const pixelsPerDay = chartWidth / totalDays;
return pixels / pixelsPerDay;
},
formatDate(date) {
return date.toISOString().split('T')[0];
},
},
Event Listeners
Ensure to clean up event listeners to prevent memory leaks.
beforeDestroy() {
document.removeEventListener('mousemove', this.onMouseMove);
document.removeEventListener('mouseup', this.onMouseUp);
},
6. Task Dependencies
Render dependency lines between tasks using SVG.
Methods
methods: {
// Get positions of task bars
getTaskPosition(task) {
const bar = this.$refs[`taskBar${task.id}`][0];
return {
x: bar.offsetLeft + bar.offsetWidth,
y: bar.offsetTop + (bar.offsetHeight / 2),
};
},
},
Render Dependency Lines
<svg class="dependency-lines">
<line
v-for="task in flatTasks"
v-for="depId in task.dependencies"
:key="`dep-${task.id}-${depId}`"
:x1="getTaskPosition(task).x"
:y1="getTaskPosition(task).y"
:x2="getTaskPosition(getTaskById(depId)).x"
:y2="getTaskPosition(getTaskById(depId)).y"
stroke="black"
marker-end="url(#arrowhead)"
/>
<!-- Define arrowhead marker -->
<defs>
<marker id="arrowhead" markerWidth="10" markerHeight="7"
refX="0" refY="3.5" orient="auto">
<polygon points="0 0, 10 3.5, 0 7" />
</marker>
</defs>
</svg>
Helper Methods
methods: {
getTaskById(id) {
return this.flatTasks.find(task => task.id === id);
},
},
7. Resource Assignment Display
Show who is working on each task in both the task tree and the Gantt chart bars.
<!-- In TaskItem.vue -->
<span class="task-resource">{{ task.resource }}</span>
<!-- In TaskBar.vue -->
<div class="task-bar-resource">{{ task.resource }}</div>
8. Styling
Use CSS to style your Gantt chart for better visuals.
.gantt-chart {
display: flex;
font-family: Arial, sans-serif;
}
.task-tree {
width: 25%;
padding: 10px;
border-right: 1px solid #ccc;
}
.chart-area {
width: 75%;
position: relative;
overflow-x: scroll;
background-color: #f9f9f9;
}
.chart-bars {
position: relative;
height: 600px; /* Adjust as needed */
}
.task-bar {
position: absolute;
height: 20px;
background-color: #69c;
border: 1px solid #036;
cursor: move;
}
.task-bar:hover {
background-color: #58b;
}
.task-bar-resource {
font-size: 10px;
text-align: center;
color: #fff;
line-height: 20px;
}
.dependency-lines {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.task-info {
display: flex;
justify-content: space-between;
}
.task-name {
font-weight: bold;
}
.task-resource {
font-style: italic;
color: #666;
}
9. Performance Optimization
For large datasets, consider:
- Virtual Scrolling: Render only the visible tasks.
- Throttling/Debouncing: Optimize event handlers for drag and resize.
- Memoization: Cache computed properties where possible.
10. Considerations and Libraries
Creating a full-featured Gantt chart from scratch is complex. You might consider using or referring to existing libraries to save time and ensure robustness.
- Vue Ganttastic: Open-source Vue component for Gantt charts.
- DayPilot: Commercial library with advanced features.
- DHTMLX Gantt: Feature-rich Gantt chart library (commercial).
These libraries can provide advanced features like:
- Cross-browser Support
- Accessibility
- Advanced Interactions
- Customizable Appearance
Important Notes:
- Data Validation: Ensure all date formats are consistent to prevent rendering issues.
- Time Zones: Be cautious with date calculations if your application supports multiple time zones.
- Testing: Thoroughly test drag-and-drop and resize functionalities for edge cases.
Feel free to customize and expand upon this foundation to suit the specific needs of your application. If you have further questions or need assistance with specific features, don't hesitate to ask!