import { nextTick, ref, unref } from 'vue';
import echarts from '@/utils/echarts';
import { computed } from 'vue';
export function useEcharts(elRef) {
let chartInstance = null;
const cacheOptions = ref({});
const getOptions = computed(() => {
return {
backgroundColor: 'transparent',
...cacheOptions.value
};
});
function getInstance() {
if (!chartInstance) {
initCharts();
}
return chartInstance;
}
function initCharts() {
const el = unref(elRef);
if (!el || !unref(el)) {
return;
}
chartInstance = echarts.init(el);
}
function setOptions(options, clear = true) {
cacheOptions.value = options;
if (unref(elRef)?.offsetHeight === 0) {
setOptions(unref(getOptions));
return;
}
nextTick(() => {
if (!chartInstance) {
initCharts();
if (!chartInstance) return;
}
clear && chartInstance?.clear();
chartInstance?.setOption(unref(getOptions));
});
}
function resize() {
chartInstance?.resize();
}
return {
setOptions,
resize,
echarts,
getInstance
};
}