事关我对于Echarts使用的那些事--其一

313 阅读1分钟

「这是我参与11月更文挑战的第2天,活动详情查看:2021最后一次更文挑战

写在前面:公司的项目偏大屏可视化一些,很多都是开发跟noc大屏相关的项目,因此,数据展示也是比较常用的.通常使用的方式为Element ui的Table表格以及进度条组件,以及最常用也最强大的Echarts!

一个超级强大和丰富的配置表,可以搭建出千千万万风格功能各异的图表,这个插件真的YYDS!

事关我对于Echarts使用的那些事--其一

话不多说进入正题. 首先就是进行插件的前置准备

官网地址:echarts.apache.org/zh/index.ht…

API地址: echarts.apache.org/zh/option.h…

演示地址: echarts.apache.org/examples/zh…

社区地址: www.makeapie.com/explore.htm…

插件安装

npm install echarts

全局引入(不推荐)

//main.js
import echarts from 'echarts

Vue.prototype.$echarts = echarts

装好之后就能直接用了

组件使用

//模板
    <div id="mycharts" ref="mycharts"> </div>

//js
data(){
    return{
        options:{
        //配置项
        }
    }
}
mounted(){
    this.initEcharts();
},
methods: {
    initEcharts(){
         let myChart = echarts.init(document.getElementById("mycharts"));
         myChart.setOption(this.options)
    }
},

//style
//给定一个容器并设置宽高
#mycharts{
    width: 600px;
    height: 600px;
}

再给大家分享一下我封装的echarts组件

chy-charts.vue

<template>
  <div
    :style="`width:${width}px;height:${height}px;`"
    class="container"
    :id="container"
    :ref="container"
  ></div>
</template>

<script>
//全部引入
import * as charts from "echarts";

//按需引入
import "echarts/lib/chart/bar";
import "echarts/lib/chart/line";
import "echarts/lib/chart/pie";
import "echarts/lib/component/tooltip";
import "echarts/lib/component/legend";
//这样也可以
import { number } from "echarts";

export default {
  props: {
  //配置项
    options: {
      type: Object,
      require: true,
      default: {},
    },
    //容器宽度
    width: {
      type: Number && String,
      default: 500,
    },
    //容器高度
    height: {
      type: Number && String,
      default: 400,
    },
    //容器唯一名称
    container: {
      type: String,
      default: "container",
    },
  },
  mounted() {
    this.initecharts();
    // this.Aecharts = charts.init(this.$refs.container);
  },
  data() {
    return {
      Aecharts: null,
    };
  },
  computed: {
    Opt() {
      return this.options;
    },
  },
  watch: {
  //容器配置改变重新渲染echarts
    Opt: {
      handler(oldval, newval) {
        this.Aecharts.setOption(newval);
      },
      deep: true,
    },
    //容器名称改变重新渲染echarts
    container: {
      handler(newval) {
        this.$nextTick(() => {
          this.Aecharts = charts.init(this.$refs[newval]);
          this.Aecharts.setOption(this.options);
        });
      },
      deep: true, //深度监听
      immediate: true, //首次监听触发
    },
  },
  methods: {
    initecharts() {},
  },
};
</script>

<style>
.container {
  width: 100%;
  height: 100%;
}
</style>

大致的思路是:正常使用是需要以下步骤 引入-> 创建容器->设置配置项->重新渲染 ,加上接口数据就是,数据请求-> 修改配置项 -> 重新渲染.

而组件的作用是: 封装功能,实现 引入组件 -> 设置配置项 ,加上接口数据就是 数据请求 -> 修改配置项.当配置项发生改变会自动监听其变化并重新渲染,并且动态传入ref保证每一个容器都不重复.

End