记录echarts在vue3中的使用

655 阅读1分钟

最近项目需要做柱状图统计表,以前没有做过这次正好学习一下使用echarts绘制柱状图

由于使用的是yarn 所以用yarn add vue-echarts 命令安装echarts

接着在main.ts中引入 import * as echarts from 'echarts'

const app = createApp(App); app.config.globalProperties.$echarts = echarts;

使用的时候先写一个容器用来放echarts绘制的图

image.png

我这边先创建了一个id为echart的div用来放图,使用document.getElementById("echart")来获取这个div

导入getCurrentInstance来获取main.ts中导入的echarts import { getCurrentInstance } from "vue";

const instance = getCurrentInstance();
//使用$echarts组件
let myChart = instance.appContext.config.globalProperties.$echarts.init(
        document.getElementById("echart")
      );

使用myChart.setOption()来配置你的图表 配置项可以看官网的介绍 我需要的是横向的柱状图 需要竖着的可以把xAxis和yAxis里边内容替换即可

  myChart.setOption(
    {
     
      //X轴
      xAxis: {
        type: "value",
      },
      //y轴
      yAxis: {
        splitLine: { show: false },
        type: "category",
        //表格数据
        data: alldata.echartsdata,
      },
      series: [
        {
          radius: "100%",
          //表格数据
          data: alldata.echartslist,
          type: "bar",
          itemStyle: {
            normal: {
            //配置柱状图颜色
              color: "#0072C3",
   
              label: {
              //添加数值显示不需要可以删除
                show: true, //开启显示

                textStyle: {
                  //数值样式
                  color: "#f6f6f6",
                  fontSize: 12,
                },
              },
            },
          },
        },
      ],
    },
    true
  );
  

写完以后发现柱状图周围有很多空白 image.png

添加 grid: { top: "3%", left: "3%", right: "4%", bottom: "3%", containLabel: true, },来配置周围的空白

image.png

到这里就实现了我的需求大家有什么问题可以留言交流。