将使用echarts的方法集中管理,避免在使用过程中的繁琐定义
// useCharts.ts
import { getCurrentInstance, onUnmounted } from 'vue';
import * as echarts from 'echarts';
interface IUseChartsParams {
refName: string;
}
export function useCharts<T = any>(condition?: IUseChartsParams) {
let chart = <any>{};
const chartInstance = getCurrentInstance();
onUnmounted(() => {
// 销毁echarts实例
chart.dispose && chart.dispose();
window.removeEventListener('resize', resizeHandler);
});
/**
*初始化
*/
function chartInit(option: any, callback?: (params: any) => void) {
if (!condition?.refName) return;
chart = echarts.init(chartInstance?.refs[condition?.refName] as any);
setOption(option);
window.addEventListener('resize', resizeHandler);
if (typeof callback === 'function') {
callback(chart);
}
}
function setOption(option: any) {
if (!option) return;
chart && chart.setOption(option);
}
function clearChart() {
chart && chart.clear();
}
function resizeHandler() {
chart && chart.resize();
}
return {
chartInit,
setOption,
clearChart,
resizeHandler,
};
}
使用方法
// index,vue
import { useCharts } from '@/services/charts.service';
const { chartInit, setOption } = useCharts({ refName: 'hiddenAreaChartRef' });
chartInit(getOptions());
function getOptions(data: Record<string, any>[]) {
const xAxis: string[] = data.map(o => o.label);
const series: Record<string, any>[] = [
{
name: '隐患个数',
type: 'bar',
barWidth: '15',
showSymbol: false,
data: data,
label: {
show: false,
position: 'top',
},
},
];
const options: Record<string, any> = {
title: {
show: false,
},
tooltip: {
trigger: 'axis',
},
toolbox: {
right: '16',
feature: {
saveAsImage: {
name: '隐患区域统计',
title: '保存为图片',
},
},
},
grid: {
top: '15%',
left: '5%',
right: '4%',
bottom: 24,
containLabel: true,
},
xAxis: {
type: 'category',
data: xAxis,
},
yAxis: {
type: 'value',
name: '隐患个数(个)',
splitLine: {
show: true,
lineStyle: {
type: 'dashed',
color: '#D5D9E3',
},
},
},
series,
};
if (data.length === 0) {
options.title = {
show: true,
text: "暂无数据",
x: "center",
y: "center",
textStyle: {
color: "#cecece",
fontWeight: "normal",
fontSize: 60,
},
};
}
return options;
}