useEcharts.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import {
  2. Ref,
  3. shallowRef,
  4. unref,
  5. onMounted,
  6. onDeactivated,
  7. onBeforeUnmount,
  8. } from "vue";
  9. import echarts from "../components/baseEcharts/config";
  10. export type EChartsCoreOption = echarts.EChartsCoreOption;
  11. const useEcharts = (elRef: Ref<HTMLDivElement>, options: EChartsCoreOption) => {
  12. const charts = shallowRef<echarts.ECharts>();
  13. const setOptions = (options: EChartsCoreOption) => {
  14. charts.value && charts.value.setOption(options);
  15. };
  16. // 初始化
  17. const initCharts = (themeColor?: Array<string>) => {
  18. const el = unref(elRef);
  19. if (!el || !unref(el)) {
  20. return;
  21. }
  22. charts.value = echarts.init(el);
  23. if (themeColor) {
  24. options.color = themeColor;
  25. }
  26. setOptions(options);
  27. };
  28. // 重新窗口变化时,重新计算
  29. const resize = () => {
  30. charts.value && charts.value.resize();
  31. };
  32. onMounted(() => {
  33. window.addEventListener("resize", resize);
  34. });
  35. // 页面keepAlive时,不监听页面
  36. onDeactivated(() => {
  37. window.removeEventListener("resize", resize);
  38. });
  39. onBeforeUnmount(() => {
  40. window.removeEventListener("resize", resize);
  41. });
  42. return {
  43. initCharts,
  44. setOptions,
  45. resize,
  46. };
  47. };
  48. export { useEcharts };