feat(chart): add useEcharts and useApexChart demo

This commit is contained in:
vben
2020-10-11 14:53:04 +08:00
parent e9536b5b7c
commit 21d0ed92df
20 changed files with 1241 additions and 23 deletions

View File

@@ -0,0 +1,37 @@
import { useTimeout } from '/@/hooks/core/useTimeout';
import { tryOnUnmounted } from '/@/utils/helper/vueHelper';
import { ref, unref, Ref, nextTick } from 'vue';
import ApexCharts from 'apexcharts';
export function useApexCharts(elRef: Ref<HTMLDivElement>) {
const chartInstanceRef = ref<Nullable<ApexCharts>>(null);
function setOptions(options: any) {
const el = unref(elRef);
if (!el || !unref(el)) {
return;
}
chartInstanceRef.value = new ApexCharts(el, options);
const chartInstance = unref(chartInstanceRef);
nextTick(() => {
useTimeout(() => {
chartInstance && chartInstance.render();
}, 30);
});
}
tryOnUnmounted(() => {
const chartInstance = unref(chartInstanceRef);
if (!chartInstance) {
return;
}
chartInstanceRef.value = null;
});
return {
setOptions,
};
}

View File

@@ -0,0 +1,79 @@
import { useTimeout } from '/@/hooks/core/useTimeout';
import { tryOnUnmounted } from '/@/utils/helper/vueHelper';
import { ref, unref, Ref, nextTick } from 'vue';
import type { EChartOption, ECharts } from 'echarts';
import echarts from 'echarts';
import { useDebounce } from '/@/hooks/core/useDebounce';
import { useEvent } from '/@/hooks/event/useEvent';
import { useBreakpoint } from '/@/hooks/event/useBreakpoint';
export type { EChartOption, ECharts };
export function useECharts(
elRef: Ref<HTMLDivElement>,
theme: 'light' | 'dark' | 'default' = 'light'
) {
const chartInstanceRef = ref<Nullable<ECharts>>(null);
let resizeFn: Fn = resize;
const [debounceResize] = useDebounce(resize, 200);
resizeFn = debounceResize;
function init() {
const el = unref(elRef);
if (!el || !unref(el)) {
return;
}
chartInstanceRef.value = echarts.init(el, theme);
useEvent({
el: window,
name: 'resize',
listener: resizeFn,
});
const { widthRef, screenEnum } = useBreakpoint();
if (unref(widthRef) <= screenEnum.MD) {
useTimeout(() => {
resizeFn();
}, 0);
}
}
function setOptions(options: any, clear = true) {
// function setOptions(options: EChartOption, clear = true) {
let chartInstance = unref(chartInstanceRef);
if (!chartInstance) {
init();
chartInstance = chartInstance = unref(chartInstanceRef);
if (!chartInstance) {
return;
}
}
clear && chartInstance.clear();
nextTick(() => {
useTimeout(() => {
chartInstance && chartInstance.setOption(options);
}, 30);
});
}
function resize() {
const chartInstance = unref(chartInstanceRef);
if (!chartInstance) {
return;
}
chartInstance.resize();
}
tryOnUnmounted(() => {
const chartInstance = unref(chartInstanceRef);
if (!chartInstance) {
return;
}
chartInstance.dispose();
chartInstanceRef.value = null;
});
return {
setOptions,
echarts,
};
}