当前位置: 首页 > news >正文

Vue3+TS+dhtmlx-gantt实现甘特图

实现样式

在这里插入图片描述

因为只做展示,所以实现很简单

实现功能

  1. 自定义列头
  2. 增加斑马线,实际结束时间(自定义实现)
  3. 自定义进度展示,根据层级让进度背景颜色变浅
  4. marker标记今天
  5. 自定义提示框内容

实现

import { gantt } from "dhtmlx-gantt"; // 引入模块
import { ref } from "vue";
import dayjs from "dayjs";
import { WorkGantt } from "@/api/information-overview/types";export const useGantt = () => {const ganttRef = ref();gantt.config.date_format = "%Y/%m/%d"; //整体格式gantt.config.duration_unit = "month"; //工期计算的基本单位gantt.config.scale_unit = "month"; //列间隔gantt.config.date_scale = "%Y/%m/%d"; //设置x轴的日期格式gantt.config.step = 1; //间隔gantt.i18n.setLocale("cn"); //中文gantt.config.autosize = true; //自适应尺寸gantt.config.autofit = true; // 表格列宽自适应gantt.config.open_tree_initially = true; // 默认是否展开树结构//只读模式gantt.config.readonly = true;// 显示网格gantt.config.show_grid = true;//更改树状的图标gantt.templates.grid_open = (item: any) => {return ("<div data-icon='" +(item.$open ? "close" : "open") +"' class='gantt_tree_icon gantt_" +(item.$open ? "close" : "open") +"'></div>");};//更改父项图标gantt.templates.grid_folder = (item: any) => {return "";};//更改子项图标gantt.templates.grid_file = (item: any) => {return "";};// timeLine 文字gantt.templates.task_text = function (start, end, task) {if (task.real_end_date) {const sizes = gantt.getTaskPosition(task,task.start_date,new Date(dayjs(task.real_end_date).format("YYYY-MM-DD")));return `<div class="real-task" style="position:absolute;left:0px;top:0px;width:${sizes.width}px;height:100%"></div>`;}return "";};// 指定工单栏已完成部分的文本gantt.templates.progress_text = function (start, end, task) {const level = task.$level as number; //层级if (task.progress) {return `<div style="text-align:right;color:#000;background-color:${adjustColor("#04aac1",level * 20,0.7)}">${Math.round(task.progress * 100)}%</div>`;}return "";};// 列配置gantt.config.columns = [{name: "keyNode",resize: true,label: "关键节点",width: 200,align: "center",tree: true,},{name: "receiver",resize: true,label: "签收人",width: 80,align: "center",},];// 开启marker插件gantt.plugins({ marker: true, tooltip: true });const today = new Date(dayjs(new Date()).format("YYYY-MM-DD"));const dateToStr = gantt.date.date_to_str(gantt.config.task_date);// 添加固定时间线gantt.addMarker({start_date: today,css: "today",text: "今日:" + dayjs(new Date()).format("YYYY-MM-DD"),title: "Today: " + dateToStr(today),});// 提示框内容gantt.templates.tooltip_text = function (start, end, task) {return `<h3>关键节点详情</h3><div class="pop-message"><span>关键节点</span><span>${task.keyNode ? task.keyNode : "暂无"}</span></div><div class="pop-message"><span>签收人</span><span>${task.receiver ? task.receiver : "暂无"}</span></div><div class="pop-message"><span>节点数量</span><span>${task.quantity}</span></div><div class="pop-message"><span>完成数量</span><span>${task.progressValue}</span></div><div class="pop-message"><span>复盘认识</span><span>${task.reflectionOnKnowledge ? task.reflectionOnKnowledge : "暂无"}</span></div><div class="pop-message"><span>复盘问题</span><span>${task.reflectionOnProblems ? task.reflectionOnProblems : "暂无"}</span></div><div class="pop-message"><span>复盘总结</span><span>${task.reflectionOnCountermeasures? task.reflectionOnCountermeasures: "暂无"}</span></div>`;};const init = (data: WorkGantt, startDate: string, endDate: string) => {gantt.config.start_date = new Date(startDate);gantt.config.end_date = new Date(endDate);gantt.init(ganttRef.value);gantt.parse(data);};const refresh = (data: WorkGantt, startDate: string, endDate: string) => {gantt.clearAll();gantt.config.start_date = new Date(startDate);gantt.config.end_date = new Date(endDate);gantt.parse(data);gantt.refreshData();};const destroyed = () => {gantt.clearAll();};return {init,refresh,ganttRef,destroyed,};
};function adjustColor(color: string, depth: number, alpha: number) {// 判断颜色格式const isRgb = color.length === 3 || color.length === 4;const isHex = /^#[0-9a-fA-F]{6}$/.test(color);if (!isRgb && !isHex) {throw new Error("Invalid color format. Accepted formats: RGB (e.g., [255, 0, 0]) or Hex (e.g., #ff0000)");}// 将RGB或十六进制颜色转为RGBA格式let rgbaColor: any;if (isRgb) {rgbaColor = [...color, alpha];} else if (isHex) {const rgbColor = hexToRgb(color) as number[];rgbaColor = [...rgbColor, alpha];}// 根据深浅值调整RGBA值rgbaColor = adjustColorValue(rgbaColor, depth);return `rgba(${rgbaColor[0]},${rgbaColor[1]},${rgbaColor[2]},${rgbaColor[3]})`;
}// 十六进制转RGB
function hexToRgb(hex: string) {const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);return result? [parseInt(result[1], 16),parseInt(result[2], 16),parseInt(result[3], 16),]: null;
}// 调整颜色深浅值和透明度
function adjustColorValue(rgba: number[], depth: number) {return [Math.round(rgba[0] + depth) > 255 ? 255 : Math.round(rgba[0] + depth),Math.round(rgba[1] + depth) > 255 ? 255 : Math.round(rgba[1] + depth),Math.round(rgba[2] + depth) > 255 ? 255 : Math.round(rgba[2] + depth),rgba[3], // 保持透明度不变];
}

使用

<template><div class="bg-white"><div class="flex justify-between p-2"><div class="flex"><el-radio-group v-model="state.type"><el-radio-button label="self">个人任务</el-radio-button><el-radio-button label="team">全局任务</el-radio-button></el-radio-group><div class="ml-8 flex items-center"><span class="font-size-4 mr-4">日期范围</span><el-date-pickerv-model="state.time"type="daterange"range-separator="至"start-placeholder="开始日期"end-placeholder="结束日期"@change="changeDate"/></div></div><el-button type="primary" @click="exportImg" :icon="Download">导出图片</el-button></div><divv-loading="state.loading"id="gantt"ref="ganttRef"class="h-full w-full"></div></div>
</template><script lang="ts">
export default { name: "ObjectProgress" };
</script>
<script lang="ts" setup>
import "dhtmlx-gantt/codebase/dhtmlxgantt.css"; //皮肤
import { onMounted, reactive } from "vue";
import html2canvas from "html2canvas";
import { useGantt } from ".";
import { Download } from "@element-plus/icons-vue";
import { gantt } from "dhtmlx-gantt";
import { getWorkGantt } from "@/api/january-post";
import { useUserStoreHook } from "@/store/modules/user";
import { WorkGantt } from "@/api/information-overview/types";
import dayjs from "dayjs";const state = reactive({tasks: {data: [],} as WorkGantt,type: "self",timelist: "",time: "",loading: false,
});
const { account } = useUserStoreHook().user;
const { init, ganttRef, refresh } = useGantt();watch(() => state.type,() => {getWorkGanttList((data, startDate, endDate) => {refresh(data, startDate, endDate);});}
);/*** @description 获取甘特图数据*/
const getWorkGanttList = (callback: (data: any, startDate: string, endDate: string) => void
) => {state.loading = true;const parmas = {type: state.type,user: account,timelist: state.timelist,};// debugger;getWorkGantt(parmas).then((response) => {const data = response.data;const handleData = data.map((item, index) => {const id = index + 1;const start_date = dayjs(item.releaseTime).format("YYYY-MM-DD");const end_date = dayjs(item.signingTime).format("YYYY-MM-DD");const real_end_date = item.completionTime? dayjs(item.completionTime).format("YYYY-MM-DD"): "";return {id,start_date,end_date,real_end_date,progress: item.progressBar,keyNode: item.keyNode,receiver: item.receiver,name: item.name,reflectionOnKnowledge: item.reflectionOnKnowledge,reflectionOnProblems: item.reflectionOnProblems,reflectionOnCountermeasures: item.reflectionOnCountermeasures,quantity: item.quantity,progressValue: item.progressValue,};});const endDate = dayjs(Math.max(...data.map((item) => [item.completionTime, item.signingTime]).flat().map((item) => new Date(item).getTime()))).format("YYYY-MM-DD");const startDate = dayjs(Math.min(...data.map((item) => item.releaseTime).map((item) => new Date(item).getTime()))).format("YYYY-MM-DD");state.tasks.data = handleData;callback(state.tasks, startDate, endDate);}).finally(() => {state.loading = false;});
};/*** @description 甘特图转canvas*/
const exportImg = () => {html2canvas(document.querySelector("#gantt")!).then(function (canvas) {downloadPng(canvas);});
};
/*** @description 下载canvas*/
const downloadPng = (el: HTMLCanvasElement) => {// 创建一个新的a元素,设置其href为canvas的toDataURL方法,并添加download属性var link = document.createElement("a");link.href = el.toDataURL("image/png");link.download = `${state.type === "personal" ? "个人任务" : "全局任务"}.png`;// 触发a元素的click事件以开始下载document.body.appendChild(link);link.click();document.body.removeChild(link);
};
/*** @description 选择日期*/
const changeDate = (date: Date[]) => {if (date) {state.timelist = date.map((item) => dayjs(item).format("YYYY/MM/DD")).join(";");} else {state.timelist = "";}getWorkGanttList((data, startDate, endDate) => {refresh(data, startDate, endDate);});
};onMounted(() => {getWorkGanttList((data, startDate, endDate) => {init(data, startDate, endDate);});
});
</script><style lang="scss" scoped>
:deep(.gantt_task_line) {background-color: #fff;border-color: rgb(220 223 230 / 100%);border-radius: 4px;.gantt_task_content {z-index: 1;overflow: initial;color: #000;}.gantt_task_progress_wrapper {z-index: 2;border-radius: 4px;}
}:deep(.gantt_task_progress) {background-color: transparent;
}:deep(.real-task) {z-index: 3;background: url("../../../../../assets/icons/diagonal-line.svg") repeat;border: 1px solid rgb(220 223 230 / 100%);border-radius: 4px;opacity: 0.5;
}:deep(.gantt_marker) {z-index: 99;
}
</style>

相关文章:

  • typing python 类型标注学习笔记
  • Vue3 Hooks函数使用及封装
  • Qt容器QMap(映射)
  • leetcode---Z字形变换
  • 数据结构<1>——树状数组
  • 汇编中的标签与C语言的函数对比与区别
  • Windows10上通过MSYS2编译FFmpeg 6.1.1源码操作步骤
  • 时间序列大模型:TimeGPT
  • 大数据平台红蓝对抗 - 磨利刃,淬精兵!
  • 搭建k8s集群实战(一)系统设置
  • 机器学习-决策树【手撕】
  • spawn_group_template | spawn_group | linked_respawn
  • 【Flink-CDC】Flink CDC 介绍和原理概述
  • 编码风格之(5)GNU软件编码风格(3)
  • c# MathNet.Numerics 圆拟合使用案例
  • 8年软件测试工程师感悟——写给还在迷茫中的朋友
  • codis proxy处理流程
  • download使用浅析
  • Java 最常见的 200+ 面试题:面试必备
  • Nginx 通过 Lua + Redis 实现动态封禁 IP
  • Octave 入门
  • Python 基础起步 (十) 什么叫函数?
  • Python学习之路13-记分
  • React+TypeScript入门
  • STAR法则
  • tweak 支持第三方库
  • Vue学习第二天
  • 初识 webpack
  • 基于web的全景—— Pannellum小试
  • 将回调地狱按在地上摩擦的Promise
  • 那些年我们用过的显示性能指标
  • 一个JAVA程序员成长之路分享
  • 一个完整Java Web项目背后的密码
  • UI设计初学者应该如何入门?
  • 测评:对于写作的人来说,Markdown是你最好的朋友 ...
  • ​iOS实时查看App运行日志
  • ​猴子吃桃问题:每天都吃了前一天剩下的一半多一个。
  • $.proxy和$.extend
  • ( )的作用是将计算机中的信息传送给用户,计算机应用基础 吉大15春学期《计算机应用基础》在线作业二及答案...
  • (Matalb分类预测)GA-BP遗传算法优化BP神经网络的多维分类预测
  • (pojstep1.3.1)1017(构造法模拟)
  • (二)windows配置JDK环境
  • (附程序)AD采集中的10种经典软件滤波程序优缺点分析
  • (附源码)springboot青少年公共卫生教育平台 毕业设计 643214
  • .NET BackgroundWorker
  • .NET C#版本和.NET版本以及VS版本的对应关系
  • .NET MVC 验证码
  • .NET 程序如何获取图片的宽高(框架自带多种方法的不同性能)
  • .net 获取url的方法
  • .net 生成二级域名
  • .NET 中的轻量级线程安全
  • .net2005怎么读string形的xml,不是xml文件。
  • .net程序集学习心得
  • .NET与java的MVC模式(2):struts2核心工作流程与原理
  • .vimrc php,修改home目录下的.vimrc文件,vim配置php高亮显示