Vue3 installation and configuration echarts

Vue3 installs and configures ECharts

Install

npm install echarts --save

Create a new echarts.ts file

// /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;

Method 1: Add echarts attribute to vue instance

The main.ts file configures echarts

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

In-component references

<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>

Method 2: Use provide/inject to pass echarts

App.vue configuration

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

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

Receiving within the component

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

Guess you like

Origin blog.csdn.net/weixin_43832353/article/details/129238239