Vue2中集成DHTMLXGantt甘特圖的步驟
Vue2中使用DHTMLX Gantt甘特圖組件
在 Vue 2 項目中集成 DHTMLX Gantt 甘特圖組件,可通過以下步驟實現(xiàn)。以下內(nèi)容綜合多個權(quán)威來源整理而成,涵蓋安裝、配置、數(shù)據(jù)綁定及常見問題解決方案:
一、安裝依賴?
?1、安裝核心包?
通過 npm 安裝 DHTMLX Gantt:
npm install dhtmlx-gantt@^7.1.13 # 推薦兼容 Vue 2 的版本[3](@ref)
二、基礎(chǔ)集成步驟?
?1. 組件初始化
<template>
<div ref="ganttContainer" style="width: 100%; height: 600px;"></div>
</template>
<script>
import "dhtmlx-gantt/codebase/dhtmlxgantt.css";
import { gantt } from "dhtmlx-gantt"; // 從模塊導(dǎo)入 gantt 對象[2,3](@ref)
export default {
mounted() {
this.initGantt();
},
methods: {
initGantt() {
// 初始化容器
gantt.init(this.$refs.ganttContainer);
// 加載示例數(shù)據(jù)
const tasks = {
data: [
{ id: 1, text: "項目計劃", start_date: "2023-07-01", duration: 5 },
{ id: 2, text: "需求分析", start_date: "2023-07-02", duration: 3, parent: 1 }
],
links: [] // 任務(wù)依賴關(guān)系
};
gantt.parse(tasks); // 解析數(shù)據(jù)并渲染[1,6](@ref)
}
}
};
</script>2. 關(guān)鍵配置項
// 時間軸與日期格式
gantt.config.scale_unit = "day"; // 刻度單位(day/week/month)
gantt.config.step = 1; // 單位間隔
gantt.config.date_scale = "%Y年%m月%d日"; // 日期顯示格式[1,4](@ref)
// 任務(wù)條樣式
gantt.config.row_height = 40; // 行高
gantt.config.bar_height = 20; // 任務(wù)條高度
// 國際化(中文支持)
gantt.i18n.setLocale("zh"); // 設(shè)置簡體中文[2](@ref)三、動態(tài)數(shù)據(jù)綁定?
?1. 從 API 加載數(shù)據(jù)
methods: {
async loadData() {
const res = await this.$axios.get("/api/tasks");
gantt.clearAll(); // 清除舊數(shù)據(jù)
gantt.parse(res.data); // 加載新數(shù)據(jù)[3,6](@ref)
}
}2. 響應(yīng)父組件數(shù)據(jù)變化
props: ["tasks"], // 接收父組件數(shù)據(jù)
watch: {
tasks(newTasks) {
gantt.parse(newTasks); // 數(shù)據(jù)更新時自動刷新[6](@ref)
}
}四、事件與交互?
?1. 事件監(jiān)聽示例
mounted() {
gantt.attachEvent("onTaskClick", (id, e) => {
this.$emit("task-click", id); // 向父組件傳遞點擊事件[6](@ref)
});
gantt.attachEvent("onAfterTaskAdd", (id, task) => {
console.log("任務(wù)添加:", task);
});
}2. 任務(wù)操作(增刪改)?
// 添加任務(wù)
gantt.addTask({ text: "新任務(wù)", start_date: "2023-07-10", duration: 2 });
// 刪除任務(wù)
gantt.deleteTask(taskId);
// 更新任務(wù)
const task = gantt.getTask(taskId);
task.text = "修改后的名稱";
gantt.updateTask(taskId);五、常見問題解決
?1、容器渲染失敗?
確保在 mounted 生命周期初始化,此時 DOM 已掛載
容器需明確設(shè)置寬高(如 style="width:100%;height:600px")
?2、數(shù)據(jù)格式錯誤?
任務(wù)必須包含 id、text、start_date、duration
日期格式需統(tǒng)一(建議 YYYY-MM-DD)
?3、多語言不生效?
檢查是否調(diào)用 gantt.i18n.setLocale("zh")
確保未覆蓋語言包文件
?4、商業(yè)功能限制?
自動調(diào)度、關(guān)鍵路徑計算等功能需企業(yè)版授權(quán)
社區(qū)版可滿足基礎(chǔ)甘特圖需求
六、最佳實踐建議?
?性能優(yōu)化?:
超過 500 條任務(wù)時,啟用虛擬滾動:
gantt.config.virtual_rendering = true; // 僅渲染可視區(qū)域[3](@ref)
樣式覆蓋?:
通過 CSS 自定義任務(wù)條顏色:
.gantt_task_line {
background-color: #4CAF50 !important;
}?版本兼容性?:
Vue 2 項目建議鎖定版本 dhtmlx-gantt@7.1.x,避免新版不兼容。
通過以上步驟,可在 Vue 2 中快速實現(xiàn)功能完整的甘特圖。如需復(fù)雜功能(如任務(wù)依賴線、資源視圖),參考 DHTMLX Gantt 官方文檔。
補充介紹:VUE2甘特圖+element-ui實現(xiàn)
VUE2甘特圖+element-ui實現(xiàn)
1.先看效果

2.引用依賴
2.1、引入Dhtmlx Gantt組件
npm install dhtmlx-gantt
3.代碼實現(xiàn)
<template>
<div class="dashboard-editor-container">
<el-row>
<el-col :span="24">
<div>
<!-- Gantt 圖區(qū)域 -->
<div id="gantt-chart" style="width: 100%; height: 800px;"></div>
</div>
</el-col>
</el-row>
</div>
</template>
<script>
// 引入 dhtmlx-gantt 的樣式和 JS 文件
import 'dhtmlx-gantt/codebase/dhtmlxgantt.css'; // 樣式文件
import gantt from 'dhtmlx-gantt'; // dhtmlx-gantt 庫
import {selectTTaskListGantt} from "@/api/system/task";
import moment from "moment";
export default {
name: 'Index',
data() {
return {}
},
mounted() {
gantt.clearAll();
//調(diào)用甘特圖初始化
this.init();
//獲取數(shù)據(jù)
this.getProductData();
},
methods: {
//初始化甘特圖
init() {
//初始化甘特圖
gantt.init("gantt-chart");
gantt.config.min_column_width = 50; // 設(shè)置為適合你需求的值
gantt.config.grid_width = 600; // 左側(cè)列表寬度
// gantt.config.min_grid_column_width = 120; // 設(shè)置調(diào)整網(wǎng)格大小時左側(cè)每一格的最小寬度---優(yōu)先于grid_width
gantt.config.scale_height = 80; // 設(shè)置時間刻度的高度和左側(cè)表格頭部高度
gantt.config.row_height = 35; //設(shè)置行高
//gantt.config.scale_width = 200; // 設(shè)置時間軸主單位的寬度為 100px
//gantt.config.column_width = 150; // 每列寬度(日期的列寬)
gantt.config.readonly = true; // 只讀模式
gantt.config.fit_tasks = true; // 是否自動延長時間范圍以適應(yīng)所有顯示的任務(wù)--效果:拖動任務(wù)時間范圍延長,可顯示區(qū)域會自動變化延長
gantt.config.autofit = true; // 寬度是否自適應(yīng)
gantt.config.show_quick_info = true; // 是否顯示quickInfo(甘特圖詳情小框)
gantt.config.work_time = true; // 是否允許在工作時間而不是日歷時間中計算任務(wù)的持續(xù)時間
// 給時間Cell添加類名
gantt.templates.timeline_cell_class = function (task, date) {
if (!gantt.isWorkTime({task: task, date: date})) return "weekend";
};
// 給對應(yīng)的時間線表格頭部添加類名
gantt.templates.scale_cell_class = function (date) {
if (!gantt.isWorkTime(date)) return "weekend";
};
// 設(shè)置甘特圖的初始日期及結(jié)束日期,也可設(shè)置動態(tài)日期
gantt.config.start_date = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDay() - 7); // 月份從0開始,0代表1月
gantt.config.end_date = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDay() + 7); // 設(shè)置結(jié)束日期為2020年12月31日
//設(shè)置日期格式
gantt.config.date_format = "%Y-%m-%d"; // 設(shè)置日期格式
//時間軸展示
gantt.config.scale_unit = "month"; // 主時間軸單位為月份
gantt.config.date_scale = "%Y年 %m月"; // 顯示月和年(例如:01 2024)
// 配置子時間軸,首先顯示月份,再顯示具體日期
gantt.config.subscales = [
{unit: "day", step: 1, date: "%d"} // 子時間軸顯示日期(例如:01, 02, 03)
];
// 配置時間軸,主單位為月,副單位為日
gantt.config.scale_unit = "month"; // 主時間單位為“月”
gantt.config.subscales = [
{unit: "day", step: 1, template: "%d日"} // 第二行:顯示日期
];
//配置列標題
gantt.config.columns = [
{
name: "taskName", label: "項目", width: 80, template: function (task) {
return `<el-table-column show-overflow-tooltip style="text-align: center; font-size: 10px; color: black;">${task.taskName}</el-table-column>`;
}
}, // 修改任務(wù)名稱的列標題
{
name: "userListString", label: "參與人", width: 60, template: function (task) {
return task.userListString.map(item => `<el-tag>${item.nickName}</el-tag>`).join(',');
// 注意:這種方法需要確保外部框架支持這種方式,并且能夠正確解析和渲染返回的 HTML 字符串
// return `<div style="text-align: center; font-size: 14px; color: black;">${task.userListString}</div>`;
}
}, // 修改開始時間的列標題
// {
// name: "start_date", label: "開始時間", width: 120, template: function (task) {
// return `<el-table-column show-overflow-tooltip style="text-align: center; font-size: 10px; color: black;"> ${gantt.date.date_to_str("%Y-%m-%d %H:%i:%s")(task.start_date)}</div>`;
// }
// }, // 修改開始時間的列標題
// {
// name: "end_date", label: "計劃完成時間", width: 120, template: function (task) {
// return `<el-table-column show-overflow-tooltip style="text-align: center; font-size: 10px; color: black;"> ${gantt.date.date_to_str("%Y-%m-%d %H:%i:%s")(task.end_date)}</div>`;
// }
// }, // 修改開始時間的列標題
// {
// name: "duration", label: "任務(wù)天數(shù)", width: 50, template: function (task) {
// return `<div style="text-align: center; font-size: 14px; color: black;">${task.duration} </div>`;
// }
// } // 修改持續(xù)時間的列標題
];
gantt.plugins({
tooltip: true, // 鼠標放上提示框
});
const taskStateOptions = {
type: {
task_state: [
{label: "待分配", value: "0"},
{label: "待啟動", value: "3"},
{label: "進行中", value: "2"},
{label: "延期中", value: "1"},
{label: "待驗收", value: "6"},
{label: "已完成", value: "4"},
{label: "已終止", value: "5"},
]
}
};
gantt.templates.tooltip_text = function (start, end, task) {
// 查找任務(wù)狀態(tài)對應(yīng)的標簽
const stateLabel = taskStateOptions.type.task_state.find(option => option.value === task.state)?.label || '未知狀態(tài)';
// 自定義tooltip的內(nèi)容
return `
<div style="display: flex; flex-wrap: wrap; align-items: center; width: 500px;">
<div style="width: 100%; line-height: 18px; font-weight: bold;">項目名稱:${task.projectName}</div>
<div style="width: 100%; line-height: 18px; font-weight: bold;">目標名稱:${task.targetName}</div>
<div style="width: 100%; line-height: 18px; font-weight: bold;">任務(wù)名稱:${task.taskName}</div>
<div style="width: 100%; line-height: 18px; font-weight: bold;">開始時間:${gantt.date.date_to_str("%Y-%m-%d %H:%i:%s")(task.start_date)}</div>
<div style="width: 100%; line-height: 18px; font-weight: bold;">計劃完成時間:${gantt.date.date_to_str("%Y-%m-%d %H:%i:%s")(task.end_date)}</div>
<div style="width: 100%; line-height: 18px; font-weight: bold;">任務(wù)狀態(tài):${stateLabel}</div>
</div>
`;
};
gantt.init("gantt-chart");
},
//甘特圖數(shù)據(jù)源
getProductData() {
selectTTaskListGantt(this.addDateRange(this.queryParamsTask, this.dateRange)).then(response => {
console.log("甘特圖數(shù)據(jù)源:", response);
if (response.code == 200) {
const data = response.rows;
console.log("數(shù)據(jù)源:", data);
// 格式化數(shù)據(jù)以匹配甘特圖的要求
const formattedData = data.map(item => ({
taskId: item.taskId,
taskName: item.taskName,
projectName: item.projectName,
targetName: item.targetName,
state: item.state,
userListString: item.userListString,
start_date: new Date(item.createTime),
end_date: new Date(item.updateTime),
end_date: new Date(item.updateTime),
duration: 0, //任務(wù)天數(shù)自動計算
}));
console.log("數(shù)據(jù)源:", formattedData);
//Bar條顏色
this.ganttBarColor(formattedData);
// 顯示到任務(wù)上的文本
gantt.templates.task_text = function (start, end, task) {
return "" + task.taskName;
};
// 使用 gantt.parse() 加載數(shù)據(jù)
gantt.parse({data: formattedData});
} else {
this.$message.error('生產(chǎn)計劃列表查詢失敗,請聯(lián)系管理員!');
}
});
},
//甘特圖Bar條顏色配置
ganttBarColor(formattedData) {
// 遍歷并根據(jù)任務(wù)的狀態(tài)動態(tài)增加 'color' 字段
formattedData.forEach(task => {
if (task.state === "0") {
task.color = "#909399"; //待分配
} else if (task.state === "1") {
task.color = "#ff4949"; //延期中
} else if (task.state === "2") {
task.color = "#ffba00"; //進行中
} else if (task.state === "3") {
task.color = "#909399"; //待啟動
} else if (task.state === "4") {
task.color = "#13ce66"; //已完成
} else if (task.state === "5") {
task.color = "#13ce66"; //已終止
} else if (task.state === "6") {
task.color = "#1890ff"; //待驗收
}
});
},
}
}
</script>
<style>
*{
font-size: 10px!important;
}
</style>
?到此這篇關(guān)于Vue2中使用DHTMLX Gantt甘特圖組件的步驟的文章就介紹到這了,更多相關(guān)vue使用DHTMLX Gantt內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vuejs2.0運用原生js實現(xiàn)簡單的拖拽元素功能示例
本篇文章主要介紹了vuejs2.0運用原生js實現(xiàn)簡單的拖拽元素功能示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-02-02
vue?proxytable代理根路徑的同時增加其他代理方式
這篇文章主要介紹了vue?proxytable代理根路徑的同時增加其他代理方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04
如何在vue3中使用滑塊檢驗vue-puzzle-verification
這篇文章主要介紹了在vue3中使用滑塊檢驗vue-puzzle-verification的相關(guān)資料,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2023-11-11

