VUE3.2项目如何使用Echarts5.4详细步骤总结

1、概念:必须理解按需引入 说白了就是在VUE页面中直接写,而且采用单独Import {} from ,然后在use的形式 。与之对应的就是一句话全部引入,或在

1、概念:必须理解按需引入

说白了就是在VUE页面中直接写,而且采用单独Import {} from ,然后在use的形式 。与之对应的就是一句话全部引入,或在man.js中配置部分重复功能综合使用。

import * as echarts from 'echarts/core';
import {
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  DataZoomComponent
} from 'echarts/components';
import { CustomChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
 
echarts.use([
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  DataZoomComponent,
  CustomChart,
  CanvasRenderer
]);

2、安装步骤

实际上有2种方式一种是npm,一种是按官网下载文件(echarts.js或echarts.mini.js)然后放入对应目录中再配置。这里推荐npm方式,因为不用去单独配置别的文件了。

①安装sass-loader :

选择 dart-sass 不选node sass (这步我开始跳过了,后来报错,因为有的例子使用了scss),我之前安装了node.js,采用下面命令直接安装:

npm install -g sass

②安装echarts:

npm install echarts --save

接下来就开始使用(如果例子中使用了$,那别忘记还要安装jquery)。

3、在.vue中直接使用:

①template区域给一个div,并署名id

<div id="main" style="width: 100%;height:80vh; "></div>

②script区域:

这里官网没有的,注意在该区域第一行就引入:

import { onMounted } from 'vue'

③script区域:

打开例子代码,官网例子中的按需导入和ESmode模式,如下图

拷贝从 import * as echarts from 'echarts/core'; 到 echarts.use([.. 段 的内容:

import * as echarts from 'echarts/core';
import {
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  DataZoomComponent
} from 'echarts/components';
import { CustomChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
 
echarts.use([
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  DataZoomComponent,
  CustomChart,
  CanvasRenderer
]);

④在export default 中写

 setup(){
    onMounted(()=>{
    /*在这里写整理好的例子(具体怎么整理看⑤⑥⑦)*/
                            })
            }

⑤先写自定义图和变量option等,比如:

var chartDom = document.getElementById('main');
var myChart = echarts.init(chartDom);
var option;
 
var HEIGHT_RATIO = 0.6;
var DIM_CATEGORY_INDEX = 0;
var DIM_TIME_ARRIVAL = 1;
var DIM_TIME_DEPARTURE = 2;
var DATA_ZOOM_AUTO_MOVE_THROTTLE = 30;
var DATA_ZOOM_X_INSIDE_INDEX = 1;
var DATA_ZOOM_Y_INSIDE_INDEX = 3;
var DATA_ZOOM_AUTO_MOVE_SPEED = 0.2;
var DATA_ZOOM_AUTO_MOVE_DETECT_AREA_WIDTH = 30;
var _draggable;
var _draggingEl;
var _dropShadow;
var _draggingCursorOffset = [0, 0];
var _draggingTimeLength;
var _draggingRecord;
var _dropRecord;
var _cartesianXBounds = [];
var _cartesianYBounds = [];
var _rawData;
var _autoDataZoomAnimator;

⑥再写好例子中的函数和定义的option(有的是makeOption函数),(不全部摘抄了,理解就行)

function renderGanttItem(params, api) {
  var categoryIndex = api.value(DIM_CATEGORY_INDEX);
  var timeArrival = api.coord([api.value(DIM_TIME_ARRIVAL), categoryIndex]);
  var timeDeparture = api.coord([api.value(DIM_TIME_DEPARTURE), categoryIndex]);
  var coordSys = params.coordSys;
  _cartesianXBounds[0] = coordSys.x;
  _cartesianXBounds[1] = coordSys.x + coordSys.width;
  _cartesianYBounds[0] = coordSys.y;
  _cartesianYBounds[1] = coordSys.y + coordSys.height;
  var barLength = timeDeparture[0] - timeArrival[0];
  // Get the heigth corresponds to length 1 on y axis.
  var barHeight = api.size([0, 1])[1] * HEIGHT_RATIO;
  var x = timeArrival[0];
  var y = timeArrival[1] - barHeight;
  var flightNumber = api.value(3) + '';
  var flightNumberWidth = echarts.format.getTextRect(flightNumber).width;
  var text =
    barLength > flightNumberWidth + 40 && x + barLength >= 180
      ? flightNumber
      : '';
  var rectNormal = clipRectByRect(params, {
    x: x,
    y: y,
    width: barLength,
    height: barHeight
  });
  var rectVIP = clipRectByRect(params, {
    x: x,
    y: y,
    width: barLength / 2,
    height: barHeight
  });
  var rectText = clipRectByRect(params, {
    x: x,
    y: y,
    width: barLength,
    height: barHeight
  });
  return {
    type: 'group',
    children: [
      {
        type: 'rect',
        ignore: !rectNormal,
        shape: rectNormal,
        style: api.style()
      },
      {
        type: 'rect',
        ignore: !rectVIP && !api.value(4),
        shape: rectVIP,
        style: api.style({ fill: '#ddb30b' })
      },
      {
        type: 'rect',
        ignore: !rectText,
        shape: rectText,
        style: api.style({
          fill: 'transparent',
          stroke: 'transparent',
          text: text,
          textFill: '#fff'
        })
      }
    ]
  };
}
option = {
    visualMap: {
      show: false,
      min: 0,
      max: 100,
      dimension: 1
    },
    legend: {
      data: rawData.counties,
      selectedMode: 'single',
      right: 100
    },
    grid: {
      left: 0,
      bottom: 0,
      containLabel: true,
      top: 80
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'value',
      scale: true
    },
    toolbox: {
      feature: {
        dataZoom: {}
      }
    },
    dataZoom: {
      type: 'inside'
    },
    series: series
  };

⑦在onMounted 中的函数中的最后再写 绘制图的语句:

myChart.setOption(option);

4、为方便理解:

VUE文件中的全部代码示例如下:

<template>
    <div>
        <div style="width: 100%; height: 20vh">
            <el-row :gutter="30">
                <el-col :span="2"><div class="grid-content ep-bg-purple" /></el-col>
                <el-col :span="12"><div class="grid-content ep-bg-purple" style="padding-top: 30px"/>
                    <el-dropdown size="large" split-button type="primary">
                        越秀店
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item>番禺店 </el-dropdown-item>
                                <el-dropdown-item>天河店</el-dropdown-item>
                                <el-dropdown-item>珠江新城店</el-dropdown-item>
                                <el-dropdown-item>南沙店</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </el-col>
                <el-col :span="8"><div class="grid-content ep-bg-purple" style="padding-top: 100px;"/>
                    <el-row class="mb-4">
                        <el-button size ="normal" type="primary">全部</el-button>
                        <el-button size ="normal" type="success">待排</el-button>
                        <el-button size ="normal" type="info">待取</el-button>
                        <el-button size ="normal" type="warning">待还</el-button>
                        <el-button size ="normal" type="danger">调配</el-button>
                    </el-row>
                </el-col>
<!--                <el-col :span="0"><div class="grid-content ep-bg-purple" /></el-col>-->
            </el-row>
        </div>
        <div id="main" style="width: 100%;height:80vh;  "></div>
    </div>
</template>
<script>
    import { onMounted } from 'vue'
    /*import $ from 'jquery'*/
    import dayjs from 'dayjs'
    /******************
     * *从这行开始往下可以复用*****
     * ********************/
    // 核心模块 提供必要的一些方法 如init
    import * as echarts from 'echarts/core';
    import {
        TitleComponent,
        TooltipComponent,
        GridComponent,
        DataZoomComponent
    } from 'echarts/components';
    import { CustomChart } from 'echarts/charts';
    import { CanvasRenderer } from 'echarts/renderers';
    echarts.use([
        TitleComponent,
        TooltipComponent,
        GridComponent,
        DataZoomComponent,
        CustomChart,
        CanvasRenderer
    ]);
    /*************
     * ***********到这完成引入,下面写变量、方法、绘制************
     * ****************/
    export default {
        name: "HomeView",
        components: {
        },
        method:{
        },
        setup(){
            onMounted(()=>{
                // 基于准备好的dom,初始化echarts实例
                var myChart = echarts.init(document.getElementById('main'));
                var option;
                //变量
                var data = [];
                var dataCount = 10;
                var startTime = +new Date();
                var categories = ['文具', '尺子', '橡皮'];
                var types = [
                    { name: 'JS Heap', color: '#7b9ce1' },
                    { name: 'Documents', color: '#bd6d6c' },
                    { name: 'Nodes', color: '#75d874' },
                    { name: 'Listeners', color: '#e0bc78' },
                    { name: 'GPU Memory', color: '#dc77dc' },
                    { name: 'GPU', color: '#72b362' }
                ];
                //format 定义需要显示的格式
                function dataFliter(val,format = "YYYY-MM-DD "
                // + "hh:mm:ss" + ""
                ){
                    return dayjs(val).format(format);
                }
                option = {
                    tooltip: {
                        formatter: function (params) {
                         return params.marker + params.name + ': ' + params.value[3] + ' ms';
                        }
                    },
                    title: {
                        text: '文具汇总',
                        left: 'center'
                    },
                    dataZoom: [
                        {
                            type: 'slider',
                            filterMode: 'weakFilter',
                            showDataShadow: false,
                            top: 400,
                            labelFormatter: ''
                        },
                        {
                            type: 'inside',
                            filterMode: 'weakFilter'
                        }
                    ],
                    grid: {
                        height: 300
                    },
                    xAxis: {
                        position:'top',
                        min: startTime,
                        scale: true,
                        axisLabel: {
                            formatter:                            
                                 function (val) {
                                 return Math.max(0, val - startTime) + ' ms';
                             }
                        }
                    },
                    yAxis: {
                        data: categories
                    },
                    series: [
                        {
                            type: 'custom',
                            renderItem: renderItem,
                            itemStyle: {
                                opacity: 0.8
                            },
                            encode: {
                                x: [1, 2],
                                y: 0
                            },
                            data: data
                        }
                    ]
                };
                //方法
                // Generate mock data
                categories.forEach(function (category, index) {
                    var baseTime = startTime;
                    for (var i = 0; i < dataCount; i++) {
                        var typeItem = types[Math.round(Math.random() * (types.length - 1))];
                        // var duration = Math.round(Math.random() * 86400000);
                        var duration = 86400000;
                        data.push({
                            name: typeItem.name,
                            value: [index, baseTime, (baseTime += duration), duration],
                            itemStyle: {
                                normal: {
                                    color: typeItem.color
                                }
                            }
                        });
                        baseTime += Math.round(Math.random() * 2000);
                    }
                });
                function renderItem(params, api) {
                    var categoryIndex = api.value(0);
                    var start = api.coord([api.value(1), categoryIndex]);
                    var end = api.coord([api.value(2), categoryIndex]);
                    var height = api.size([0, 1])[1] * 0.6;
                    var rectShape = echarts.graphic.clipRectByRect(
                        {
                            x: start[0],
                            y: start[1] - height / 2,
                            width: end[0] - start[0],
                            height: height
                        },
                        {
                            x: params.coordSys.x,
                            y: params.coordSys.y,
                            width: params.coordSys.width,
                            height: params.coordSys.height
                        }
                    );
                    return (
                        rectShape && {
                            type: 'rect',
                            transition: ['shape'],
                            shape: rectShape,
                            style: api.style()
                        }
                    );
                }
                // 绘制图表
                myChart.setOption(option);
            })
        }
    }
</script>
<style  scoped>
</style>

5、遇到的问题:

①如果官网例子中使用到$:

记得要先安装jquery,可以采用npm安装,不然会报错

② 如果例子中使用了官网地址(主要是个json文件):

涉及到跨域的问题,我是把json放在项目文件中来解决的,分2步:

先把那个json文件放到public目录下(便于统一管理,且放在这里更符合规范)

然后在$ 中把拼接的地址直接换成/XXX.json

到这里你就可以用起来了,剩下的慢慢摸索属性,做出自己想要的图案,分享出来供大家参考,希望少走我走过的弯路。

总结

到此这篇关于VUE3.2项目使用Echarts5.4的文章就介绍到这了,更多相关VUE3.2使用Echarts5.4内容请搜索好代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好代码网!

您可能有感兴趣的文章
vue-element-admin中node-sass换成dart-sass,安装依赖报code 128多种问题的如何解决方法

大前端代码重构之事件拦截iOS Flutter Vue示例分析

详解vue样式穿透的几种方式

vue项目中安装less依赖的过程

Vue3 重构函数透传示例解析