index.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { ref, onMounted, onUnmounted, getCurrentInstance } from 'vue'
  2. import { timerInterceptor } from '@/utils/timer'
  3. import { echarts, ECOption } from './core'
  4. import ResizeObserver from 'resize-observer-polyfill'
  5. // 默认配置项
  6. const defaultOption: ECOption = {
  7. backgroundColor: 'transparent',
  8. animation: false,
  9. grid: {
  10. top: 20,
  11. bottom: 40,
  12. },
  13. axisPointer: {
  14. show: true,
  15. triggerTooltip: false,
  16. },
  17. }
  18. export function useEcharts() {
  19. const context = getCurrentInstance();
  20. const chartElement = ref<HTMLElement>(); // chart 元素
  21. let chart: echarts.ECharts; // chart 对象
  22. // 图表配置项
  23. const setOptions = (option: ECOption, notMerge = false) => {
  24. chart?.setOption(option, notMerge);
  25. }
  26. // 图表初始化
  27. onMounted(() => {
  28. const el = chartElement.value;
  29. if (el) {
  30. // 初始化图表
  31. chart = echarts.init(el);
  32. chart.setOption(defaultOption);
  33. chart.off('mousemove');
  34. // 监听鼠标滑动
  35. chart.getZr().on('mousemove', (params) => {
  36. const pointInPixel = [params.offsetX, params.offsetY];
  37. if (chart.containPixel('grid', pointInPixel)) {
  38. const pointInGrid = chart.convertFromPixel({ seriesIndex: 0 }, pointInPixel)
  39. const dataIndex = pointInGrid[0];
  40. context?.emit('update:dataIndex', dataIndex);
  41. }
  42. })
  43. // 图表重置大小
  44. const resize = timerInterceptor.setDebounce(() => {
  45. chart.resize && chart.resize();
  46. }, 50);
  47. // 监听元素变化
  48. const resizeObserver = new ResizeObserver(resize);
  49. resizeObserver.observe(el);
  50. context?.emit('ready', chart);
  51. onUnmounted(() => {
  52. resizeObserver.unobserve(el);
  53. chart.dispose();
  54. })
  55. }
  56. })
  57. return {
  58. chartElement,
  59. setOptions
  60. }
  61. }