vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vue使用DHTMLX Gantt

Vue2中集成DHTMLXGantt甘特图的步骤

作者:duansamve

文章介绍了在Vue2中集成DHTMLXGantt甘特图的步骤,涵盖安装、初始化、数据绑定、事件交互及常见问题解决,感兴趣的朋友跟随小编一起看看吧

Vue2中使用DHTMLX Gantt甘特图组件

在 Vue 2 项目中集成 DHTMLX Gantt 甘特图组件,可通过以下步骤实现。以下内容综合多个权威来源整理而成,涵盖安装、配置、数据绑定及常见问题解决方案:

一、安装依赖​

​1、安装核心包​

通过 npm 安装 DHTMLX Gantt:

npm install dhtmlx-gantt@^7.1.13  # 推荐兼容 Vue 2 的版本[3](@ref)

二、基础集成步骤​

​1. 组件初始化

<template>
  <div ref="ganttContainer" style="width: 100%; height: 600px;"></div>
</template>
<script>
import "dhtmlx-gantt/codebase/dhtmlxgantt.css";
import { gantt } from "dhtmlx-gantt"; // 从模块导入 gantt 对象[2,3](@ref)
export default {
  mounted() {
    this.initGantt();
  },
  methods: {
    initGantt() {
      // 初始化容器
      gantt.init(this.$refs.ganttContainer);
      // 加载示例数据
      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: [] // 任务依赖关系
      };
      gantt.parse(tasks); // 解析数据并渲染[1,6](@ref)
    }
  }
};
</script>

2. 关键配置项

// 时间轴与日期格式
gantt.config.scale_unit = "day";       // 刻度单位(day/week/month)
gantt.config.step = 1;                // 单位间隔
gantt.config.date_scale = "%Y年%m月%d日"; // 日期显示格式[1,4](@ref)
// 任务条样式
gantt.config.row_height = 40;          // 行高
gantt.config.bar_height = 20;          // 任务条高度
// 国际化(中文支持)
gantt.i18n.setLocale("zh");            // 设置简体中文[2](@ref)

三、动态数据绑定​

​1. 从 API 加载数据

methods: {
  async loadData() {
    const res = await this.$axios.get("/api/tasks");
    gantt.clearAll();                 // 清除旧数据
    gantt.parse(res.data);            // 加载新数据[3,6](@ref)
  }
}

2. 响应父组件数据变化

props: ["tasks"], // 接收父组件数据
watch: {
  tasks(newTasks) {
    gantt.parse(newTasks); // 数据更新时自动刷新[6](@ref)
  }
}

四、事件与交互​

​1. 事件监听示例

mounted() {
  gantt.attachEvent("onTaskClick", (id, e) => {
    this.$emit("task-click", id); // 向父组件传递点击事件[6](@ref)
  });
  gantt.attachEvent("onAfterTaskAdd", (id, task) => {
    console.log("任务添加:", task);
  });
}

2. 任务操作(增删改)​

// 添加任务
gantt.addTask({ text: "新任务", start_date: "2023-07-10", duration: 2 });
// 删除任务
gantt.deleteTask(taskId);
// 更新任务
const task = gantt.getTask(taskId);
task.text = "修改后的名称";
gantt.updateTask(taskId);

五、常见问题解决

​1、容器渲染失败​

确保在 mounted 生命周期初始化,此时 DOM 已挂载

容器需明确设置宽高(如 style="width:100%;height:600px")

​2、数据格式错误​

任务必须包含 id、text、start_date、duration

日期格式需统一(建议 YYYY-MM-DD)

​3、多语言不生效​

检查是否调用 gantt.i18n.setLocale("zh")

确保未覆盖语言包文件

​4、商业功能限制​

自动调度、关键路径计算等功能需企业版授权

社区版可满足基础甘特图需求

六、最佳实践建议​

​性能优化​:

超过 500 条任务时,启用虚拟滚动:

gantt.config.virtual_rendering = true; // 仅渲染可视区域[3](@ref)

样式覆盖​:

通过 CSS 自定义任务条颜色:

.gantt_task_line {
  background-color: #4CAF50 !important;
}

​版本兼容性​:

Vue 2 项目建议锁定版本 dhtmlx-gantt@7.1.x,避免新版不兼容。

通过以上步骤,可在 Vue 2 中快速实现功能完整的甘特图。如需复杂功能(如任务依赖线、资源视图),参考 DHTMLX Gantt 官方文档。

补充介绍:VUE2甘特图+element-ui实现

VUE2甘特图+element-ui实现

1.先看效果

2.引用依赖

2.1、引入Dhtmlx Gantt组件

npm install dhtmlx-gantt

3.代码实现

<template>
  <div class="dashboard-editor-container">
    <el-row>
      <el-col :span="24">
        <div>
          <!-- Gantt 图区域 -->
          <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();
      //调用甘特图初始化
      this.init();
      //获取数据
      this.getProductData();
    },
    methods: {
      //初始化甘特图
      init() {
        //初始化甘特图
        gantt.init("gantt-chart");
        gantt.config.min_column_width = 50; // 设置为适合你需求的值
        gantt.config.grid_width = 600; // 左侧列表宽度
        // gantt.config.min_grid_column_width = 120; // 设置调整网格大小时左侧每一格的最小宽度---优先于grid_width
        gantt.config.scale_height = 80; // 设置时间刻度的高度和左侧表格头部高度
        gantt.config.row_height = 35; //设置行高
        //gantt.config.scale_width = 200; // 设置时间轴主单位的宽度为 100px
        //gantt.config.column_width = 150; // 每列宽度(日期的列宽)
        gantt.config.readonly = true; // 只读模式
        gantt.config.fit_tasks = true; // 是否自动延长时间范围以适应所有显示的任务--效果:拖动任务时间范围延长,可显示区域会自动变化延长
        gantt.config.autofit = true; // 宽度是否自适应
        gantt.config.show_quick_info = true; // 是否显示quickInfo(甘特图详情小框)
        gantt.config.work_time = true; // 是否允许在工作时间而不是日历时间中计算任务的持续时间
        // 给时间Cell添加类名
        gantt.templates.timeline_cell_class = function (task, date) {
          if (!gantt.isWorkTime({task: task, date: date})) return "weekend";
        };
        // 给对应的时间线表格头部添加类名
        gantt.templates.scale_cell_class = function (date) {
          if (!gantt.isWorkTime(date)) return "weekend";
        };
        // 设置甘特图的初始日期及结束日期,也可设置动态日期
        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); // 设置结束日期为2020年12月31日
        //设置日期格式
        gantt.config.date_format = "%Y-%m-%d"; // 设置日期格式
        //时间轴展示
        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>`;
            }
          },  // 修改任务名称的列标题
          {
            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: "任务天数", width: 50, template: function (task) {
          //     return `<div style="text-align: center; font-size: 14px; color: black;">${task.duration} </div>`;
          //   }
          // }   // 修改持续时间的列标题
        ];
        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) {
          // 查找任务状态对应的标签
          const stateLabel = taskStateOptions.type.task_state.find(option => option.value === task.state)?.label || '未知状态';
          // 自定义tooltip的内容
          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;">任务名称:${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;">任务状态:${stateLabel}</div>
            </div>
        `;
        };
        gantt.init("gantt-chart");
      },
      //甘特图数据源
      getProductData() {
        selectTTaskListGantt(this.addDateRange(this.queryParamsTask, this.dateRange)).then(response => {
          console.log("甘特图数据源:", response);
          if (response.code == 200) {
            const data = response.rows;
            console.log("数据源:", data);
            // 格式化数据以匹配甘特图的要求
            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, //任务天数自动计算
            }));
            console.log("数据源:", formattedData);
            //Bar条颜色
            this.ganttBarColor(formattedData);
            // 显示到任务上的文本
            gantt.templates.task_text = function (start, end, task) {
              return "" + task.taskName;
            };
            // 使用 gantt.parse() 加载数据
            gantt.parse({data: formattedData});
          } else {
            this.$message.error('生产计划列表查询失败,请联系管理员!');
          }
        });
      },
      //甘特图Bar条颜色配置
      ganttBarColor(formattedData) {
        // 遍历并根据任务的状态动态增加 '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>
​

到此这篇关于Vue2中使用DHTMLX Gantt甘特图组件的步骤的文章就介绍到这了,更多相关vue使用DHTMLX Gantt内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文