Quick BI 自定义组件开发 -- 第二篇 添加 echart 组件,开发图表
文章目录
- 一、在创建自定义组件后,添加 echarts 的CDN引入
- 二、创建 echart 图表
- 2.1 DOM操作
- 2、ECharts 集成
- 3、静态数据 (正式组件使用动态数据)
- 4、生命周期管理
- 5、错误预防
- 6、 创建并导出组件
一、在创建自定义组件后,添加 echarts 的CDN引入
https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js
二、创建 echart 图表
2.1 DOM操作
- 使用
document.createElement('div')
创建chartContainer
, 作为 ECharts 的渲染容器。 - 设置样式:
import { createBIComponent } from 'bi-open-sdk';class EChartsComponent {chart = null;render(props) {// 防御性检查:确保 props 和 container 存在if (!props || !props.container) {console.error('Props or container is undefined');return;}// 清空容器props.container.innerHTML = '';// 创建图表容器const chartContainer = document.createElement('div');chartContainer.style.cssText = `// width: 600px; // height: 400px;//如果指定了宽高,拖动无法自适应大小,所以设置为百分比width: 100%;height: 100%;margin: 0 auto;padding: 0px`;}
}
- 通过
props.container.appendChild(chartContainer)
将容器添加到 Quick BI 提供的父容器。
// 将容器添加到 props.container
props.container.appendChild(chartContainer);
2、ECharts 集成
- 在
mount
方法中检查window.echarts
是否存在,不存在则提示错误
// 检查 EChars 是否加载
if (!window.echarts) {console.error('ECharts library not loaded');return;
}
- 使用
echarts.inti(chartContainer)
初始化图表实例 - 配置简单的柱状图(
option
), 显示静态数据(categories
和values
)。
// 初始化 ECharts 实例
this.chart = window.echarts.init(chartContainer);// 获取数据 -- 优化动态数据
const data = {categories : ['A', 'B', 'C', 'D'],values : [120, 200, 150, 80]
};
- 配置ECharts图
// 配置 ECharts 图
const option = {xAxis: {type: 'category',data: data.categories},yAxis: {type: 'value'},series: [{type: 'bar',data: data.values,itemStyle:{color: '#007bff'}}]
}// 渲染图表
this.chart.setOption(option)
3、静态数据 (正式组件使用动态数据)
- 目前使用硬编码数据
categories: ['A', 'B', 'C','D']
values: [120, 200, 150, 80]
- 正式组件拓展为动态数据获取
props.customProps.viewConfig
或props.customProps.data
const viewConfig = props.customProps?.viewConfig || {};
const data = viewConfig.data || { categories: ['A', 'B', 'C', 'D'], values: [120, 200, 150, 80] };
4、生命周期管理
mount
初始化ECharts, 加载图表
mount(props) {console.log('Trigger when AI component mounts');// 检查 props props.container 避免错误if (props && props.container) {props.container.classList.add('ai-component');this.render(props);} else {console.error('Mount failed: props or container is undefined');}}
update
重新渲染图表(数据更新时调用)
update(props) {console.log('trigger when component update');this.render(props);}
unmount
清空容易并销毁 ECharts 实例,(chart.dispose()
) ,防止内存泄漏。
unmount(props) {console.log('Trigger when AI component unmounts');if (props && props.container) {props.container.innerHTML = ''; // 清空容器if (this.chart) {this.chart.dispose(); // 销毁 ECharts 实例this.chart = null;}}
}
5、错误预防
- 检查
props
和props.container
,避免undefined
错误。 - 检车
windows.echarts
, 确保 ECharts 库加载成功。
6、 创建并导出组件
export const { bootstrap, mount, unmount, update } = createBIComponent({element: EChartsComponent,
});