淘先锋技术网

首页 1 2 3 4 5 6 7

Vue3 安装并配置 ECharts

安装

npm install echarts --save

新建echarts.ts文件

// /src/utils/echarts.ts
// 摘抄echarts官网:https://echarts.apache.org/handbook/zh
import * as echarts from 'echarts/core';
import {
  BarChart,
  // 系列类型的定义后缀都为 SeriesOption
  BarSeriesOption,
  LineChart,
  LineSeriesOption
} from 'echarts/charts';
import {
  TitleComponent,
  // 组件类型的定义后缀都为 ComponentOption
  TitleComponentOption,
  TooltipComponent,
  TooltipComponentOption,
  GridComponent,
  GridComponentOption,
  // 数据集组件
  DatasetComponent,
  DatasetComponentOption,
  // 内置数据转换器组件 (filter, sort)
  TransformComponent
} from 'echarts/components';
import { LabelLayout, UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';

// 通过 ComposeOption 来组合出一个只有必须组件和图表的 Option 类型
export type ECOption = echarts.ComposeOption<
  | BarSeriesOption
  | LineSeriesOption
  | TitleComponentOption
  | TooltipComponentOption
  | GridComponentOption
  | DatasetComponentOption
>;

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  BarChart,
  LineChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer
]);

export default echarts;

方法一:为vue实例新增echarts属性

main.ts文件配置echarts

// 核心代码
import eCharts from './utils/echarts';
const app = createApp(App);
app.config.globalProperties.$eCharts = eCharts;

组件内引用

<template>
  <div ref="chartEx"></div>
</template>

<script lang="ts">
import { getCurrentInstance, nextTick, ref } from 'vue';
import { ECOption } from '@/utils/echarts';
export default {
  setup() {
  	// 获取echarts
    const app: any = getCurrentInstance();
    const eCharts: any = app.appContext.config.globalProperties.$eCharts;
    // 基于准备好的dom,初始化echarts实例
    const chartEx: any = ref(null);
    const option: ECOption = {
      // 配置项
    };
    nextTick(() => {
      const myChart: any = eCharts.init(chartEx.value);
      // 绘制图表
      myChart.setOption(option);
    });

    return { chartEx };
  },
};
</script>

方法二:使用provide/inject传递echarts

App.vue配置

// 核心代码
import { provide } from 'vue';
import eCharts from './utils/echarts';

export default {
  setup() {
  	// 向下传递eCharts
    provide('eCharts', eCharts);
  },
};

组件内接收

// 核心代码
import { inject } from 'vue'
export default {
  setup() {
    const eCharts: any = inject('eCharts');
  }
}