关于Vue3中Echarts图表的引入与使用

915 阅读1分钟

不同于Echarts图表在普通html项目中的引入,在Vue3中Echarts图表的使用另辟蹊径

众所周知,常规引入是这样的

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>ECharts</title>
    <!-- 引入刚刚下载的 ECharts 文件 -->
    <script src="echarts.js"></script>
  </head>
  <body>
    <!-- 为 ECharts 准备一个定义了宽高的 DOM -->
    <div id="main" style="width: 600px;height:400px;"></div>
    <script type="text/javascript">
      // 基于准备好的dom,初始化echarts实例
      const myChart = echarts.init(document.getElementById('main'));

      // 指定图表的配置项和数据
      const option = {
        title: {
          text: 'ECharts 入门示例'
        },
        tooltip: {},
        legend: {
          data: ['NUM']
        },
        xAxis: {
          data: ['1', '2', '3', '4', '5', '6']
        },
        yAxis: {},
        series: [
          {
            name: 'NUM',
            type: 'bar',
            data: [5, 20, 36, 10, 10, 20]
          }
        ]
      };

      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    </script>
  </body>
</html>

效果: image.png

但是在Vue3中并不能通过id选择器的方式引入

1、按需引入echarts

下载依赖包

npm i echarts --save

yarn add echarts --save

在页面中引入或在main.js、main.ts中全局引入

import * as echarts from 'echarts'

2、通过ref获取dom实例

<div ref="main" style="width: 100%; height: 400px"></div>

<script setup>
import { ref } from "vue"
// 使用ref创建虚拟DOM引用,使用时用main.value
const main = ref()
</script>

3、创建方法初始化Echarts实例

    function init() {
      // 基于准备好的dom,初始化echarts实例
      const myChart = echarts.init(main.value)
      // 指定图表的配置项和数据
      const option = {
        title: {
          text: 'ECharts 示例'
        },
        tooltip: {},
        legend: {
          data: ['NUM']
        },
        xAxis: {
          data: ['1', '2', '3', '4', '5', '6']
        },
        yAxis: {},
        series: [{
          name: 'NUM',
          type: 'bar',
          data: [5, 20, 36, 10, 10, 20]
        }]
      };
      myChart.setOption(option);
    }

4、将准备好的方法挂载到onMounted生命周期

import { onMounted } from "vue"
onMounted(
  () => {
    init()
  }
)

完整代码:

<template>
	<div ref="main" style="width: 100%; height: 400px"></div>
</template>

<script setup>
import * as echarts from "echarts"
import { ref, onMounted } from "vue"
    
// 使用ref创建虚拟DOM引用,使用时用main.value
const main = ref()
onMounted(
  () => {
    init()
  }
)
    function init() {
      // 基于准备好的dom,初始化echarts实例
      const myChart = echarts.init(main.value)
      // 指定图表的配置项和数据
      const option = {
        title: {
          text: 'ECharts 示例'
        },
        tooltip: {},
        legend: {
          data: ['NUM']
        },
        xAxis: {
          data: ['1', '2', '3', '4', '5', '6']
        },
        yAxis: {},
        series: [{
          name: 'NUM',
          type: 'bar',
          data: [5, 20, 36, 10, 10, 20]
        }]
      };
      myChart.setOption(option);
    }
  myChart.setOption(option);
}
</script>