Shall I use this article to describe how I implemented my own encapsulation of Echarts very simply

First you have to go to the official website to download the plugin. I downloaded it to my project according to NPM install Echarts --save

1. Then wrap the code yourself

No more nonsense, on the code:

<template> <div> <div :style="styleE ? styleE : 'width:50%; height:200px; '" :ref="eRef"></div> </div> </template> <script> import echarts from 'echarts'; export default { props: { styleE: { default: '' }, chartData: { type: Object, default: () => {} }, eRef: { default: }, data() {return {count: 1, myChart: "}; }, methods: {drawChart() {this.mychart = echarts.init(this.refs [this.eref]);}, methods: {drawChart() {this.mychart = echarts.init(this.refs [this.eref]); MyChart. SetOption (this.chartData); }, reloadEcharts(val) { this.myChart.setOption(val, true); this.myChart.on('click', this.method); } }, mounted() { const vm = this; vm.$nextTick(() => { vm.drawChart(); }); }, created: () => {} }; </script> <style scoped></style>Copy the code
  • So our Echrats are individually packaged into a component. How about that? Simple, right?
  • So let’s do the second step, import it into the required file

Nonsense not to say, the code ~

<template> <div> <! > <my-echarts eRef="echarts" ref="barByYear1" :styleE="styleE" :chartData="chartDataByYear1"></my-echarts> <! "> <div style=" max-width: 100%; height:650px;" > <my-echarts :styleE="stylePie" eRef="pie2" :method="clickProductLine1" ref="pieByProductLine1" :chartData="pieByProductLine1"></my-echarts> </div> </div> </template>Copy the code

The js section does the imported configuration, so write it separately:

2. Write the corresponding JS logic

Take the year chart as an example!!

The code:

<script>
import myEcharts from '@/components/echarts'; // Introduce self-wrapping echarts
import {
  echartsColor, // The color of the chart
  echartsFeature, // Bar chart Stack bar chart data view
  echartsAxisLabel, // The Y-axis data is too large and ends with k M B
  pieTooltip, // The tooltip of the pie chart
  formatterThousands, // The bar chart shows the data in kiloliter format
  grid, // Control the size of the graph
  barsGrid, // Controls the size of the stack bar chart
  labelFormatter, // Label formatter and keep a decimal number
  formatterThousandsAndPercentage, // The bar graph tooltip displays data in thousandth and percentage formats
  formatterPercentage, // Stack bar graph tooltip displays data in percentage format
  tableListByYearMonth, // Table data tableListByYear
  tableListByCountry, // Table data tableListByCountry
  getDataByYear, // Get ByYear table and bar graph methods
  getDataByCountry, // Get ByCountry tables and bars
} from './common.js';
export default {
components: {
  myEcharts
},
 data () {
  return {
  / / echarts configuration
  // Year chart
  chartDataByYear1: {
    color: echartsColor(),
    tooltip: {
      trigger: 'axis'.axisPointer: {
        type: 'cross'.crossStyle: {
          color: '# 999'}},formatter: formatterThousandsAndPercentage()
    },
    toolbox: {
      top: 45.show: true.feature: echartsFeature(this)},title: {
      // Chart title
      show: true.text: 'Chart title'.textAlign: 'center'.left: '50%'.textStyle: {
        fontSize: 14.lineHeight: 20}},legend: {
      // Chart button
      data: [
        'Chart button 1'.'Chart button 2'.'Chart button 3'.'Chart button 4'].top: '25'
    },
    xAxis: [
      / / the x axis
      {
        type: 'category'.data: [ 1.2.3.4.5.6.7.8.9.10.11.12].// This is optional
        nameLocation: 'start'.// The axis name displays the position.
        axisPointer: {
          type: 'shadow'}}].yAxis: [
      / / y
      {
        type: 'value'.axisLabel: echartsAxisLabel(),
        splitLine: {
          show: false}}, {type: 'value'.axisLabel: {
          show: true.interval: 'auto'.formatter: '{value}%'
        },
        splitLine: {
          show: false
        },
        show: true}].grid: grid(),
    series: [
      // Where the button is clicked in the table
      {
        name: 'Chart button 1'.type: 'bar'.data: [].label: {
          normal: {
            position: 'top'.show: true.formatter: formatterThousands()
          }
        }
      },
      {
        name: 'Chart button 2'.type: 'bar'.barGap: '0'.// Reduce the gaps between columns by 20% by default
        data: [].label: {
          normal: {
            position: 'top'.show: true.formatter: formatterThousands()
          }
        }
      },
      {
        name: 'Chart button 3'.type: 'line'.yAxisIndex: 1.data: [].label: {
          normal: {
            position: 'top'.show: true.formatter: '{c}%'}}}, {name: 'Chart button 4'.type: 'line'.yAxisIndex: 1.data: [].label: {
          normal: {
            position: 'top'.show: true.formatter: '{c}%'}}}]},// Pie chart configuration
pieByProductLine1: {
  title: {
    text: 'Pie chart title'.subtext: ' '.left: 'center'.textStyle: {
      fontSize: 14.lineHeight: 20}},tooltip: pieTooltip(),
  color: echartsColor(),
  series: [{name: 'Pie chart with caption'.type: 'pie'.radius: '55%'.center: [ '50%'.'50%'].data: [ 0].label: labelFormatter(),
      emphasis: {
        itemStyle: {
          shadowBlur: 10.shadowOffsetX: 0.shadowColor: 'rgba (0, 0, 0, 0.5)'}}}]},// Bar chart configuration
  bars1: {
    tooltip: {
      trigger: 'axis'.axisPointer: {
        // Axis indicator. Axis trigger works
        type: 'shadow' / / the default value is linear, optional: 'the line' | 'shadow'
      },
      formatter: formatterPercentage()
    },
    title: {
      show: true.text: 'Bar chart title'.subtext: 'Monthly Sales Ratio Trend (Dollar dimension)'.textAlign: 'center'.left: '50%'.textStyle: {
        fontSize: 14.lineHeight: 20}},toolbox: {
      top: 50.show: true.feature: echartsFeature(this)},color: echartsColor(),
    legend: {
      // type: 'scroll',
      data: [].bottom: 0
    },
    xAxis: {
      type: 'category'.data: [ 1.2.3.4.5.6.7.8.9.10.11.12]},yAxis: [{type: 'value'.axisLabel: {
          show: true.interval: 'auto'.formatter: '{value}%'}}].grid: barsGrid(),
    series: []
  },
 }
}
   </script>
Copy the code

Perfect! So we can reference our own encapsulated chart

So let’s configure the chart file configuration item:

  • 1. Bar chart Data view of stacked bar charts
export function echartsFeature (that) {
  return {
    myFull: {
      show: true.title: 'View larger image'.icon: 'Your own icon',
      onclick (e) {
        that.dialogFullVisible = true
        let opts = e.getOption()
        opts.toolbox[0].feature.myFull.show = false
        setTimeout(() = > {
          that.$refs.fullEchart.reloadEcharts(opts)
          window.onresize = that.$refs.fullEchart.myChart.resize()
        }, 1000)}},dataView: {
      readOnly: true.show: true.title: 'Data view',
      optionToContent (opt) {
        let axisData = opt.xAxis[0].data;
        let series = opt.series;
        let tdHeads = ' name < / td > ';
        series.forEach(function (item) {
          tdHeads +=
            ' ' + item.name + '</td>';
        });
        let table =
          '
      
         '
        
+ tdHeads + '</tr>'; let tdBodys = ' '; for (let i = 0, l = axisData.length; i < l; i++) { for (let j = 0; j < series.length; j++) { tdBodys += ' ' + series[j].data[i] + '</td>'; } table += ' ' + axisData[i] + '</td>' + tdBodys + '</tr>'; tdBodys = ' '; } table += '</tbody></table>'; returntable; }},mark: { show: true }, magicType: { show: true.type: [ 'line'.'bar']},restore: { show: true }, saveAsImage: { show: true}}}Copy the code
  • 2. Common colors for charts
export function echartsColor () {
  return [ '# 666666'.'# 003399'.'#FFB6C1'.'#77DDFF'.'#66CC99'.'# 339999'.'# 006699'.'# 000066'.'# 999999'.'#66CC66'.'# 009966'.'# 660066'.'# 330099'.'#556B2F'.'# 778899'.'# 003377'.'#6A5ACD'.'#D8BFD8']}Copy the code
  • 3. The Y-axis data is too large and ends in K, M and B (PS: it depends entirely on personal needs)
export function echartsAxisLabel () {
  return {
    margin: 2,
    formatter (value) {
      if (value >= 1000 && value < 1000000) {
        value = value / 1000 + 'K ';
      } else if (value >= 1000000 && value < 1000000000) {
        value = value / 1000000 + 'M ';
      } else if (value >= 1000000000) {
        value = value / 1000000000 + 'B ';
      }
      if (value > -1000000 && value <= -1000) {
        value = value / 1000 + 'K ';
      } else if (value > -1000000000 && value <= -1000000) {
        value = value / 1000000 + 'M ';
      } else if (value <= -1000000000) {
        value = value / 1000000000 + 'B ';
      }
      return ' ' + value + ' '; }}}Copy the code
  • 4. Tooltips for pie charts
export function pieTooltip () {
  return {
    trigger: 'item'.// formatter: '{a} <br/>{b} : {c} ({d}%)'
    formatter (data) {
      // console.log(data, 'data')
      return data.seriesName + '<br/>' + data.name + ':' + data.value + '(' + data.percent.toFixed(2) + '%)'; }}}Copy the code
  • 5.grid
export function grid () {
  return { // Control the size of the graph by adjusting the following values:
    // show:true,// Whether to display the cartesian grid. [ default: false ]
    left: '10%'.// The distance between grid components and the left side of the container.
    right: '10%'.// borderColor:"#c45455",// the borderColor of the grid
    bottom: '25%'.//
    top: '17%'}}export function barsGrid () {
  return { // Control the size of the graph by adjusting the following values:
    // show:true,// Whether to display the cartesian grid. [ default: false ]
    left: '10%'.// The distance between grid components and the left side of the container.
    right: '10%'.// borderColor:"#c45455",// the borderColor of the grid
    bottom: '25%'.//
    top: '17%'}}Copy the code
  • 6. Bar chart shows data in milliliter format (PS: it depends entirely on personal needs)
export function formatterThousands () {
  return function (a) {
    let value = []
    if (a.data > 0) {
      value = a.data
      if (value > 999) {
        // The value is followed by a semicolon
        let parts = value.toString().split('. ')
        parts[0] = parts[0].replace(/\B(? =(\d{3})+(? ! \d))/g.', ')
        value = parts.join('. ')}}return value
  }
}
Copy the code
  • 7. The histogram tooltip displays data in millennial and percentage formats
export function formatterThousandsAndPercentage () {
  return function (params) {
    let html = params[0].name + '<br>';
    for (let i = 0; i < params.length; i++) {
      html += ' + params[i].color + ';" >'
      if (params[i].seriesName == 'Growth Rate Year-on-Year' || params[i].seriesName == 'Growth Rate Month-on-Month') {
        html += params[i].seriesName + ':' + params[i].value + '%<br>';
      } else {
        html += params[i].seriesName + ':' + Number(params[i].value).toString().replace(/\B(? =(\d{3})+(? ! \d))/g.', ') + '<br>'; }}returnhtml; }}Copy the code
  • 8. Label chart formatter and keep a decimal number (generally our numerical path will be separated by delimiter to some extent, here also the same encapsulation, or depends on personal needs)
export function labelFormatter () {
  return {
    normal: {
      show: true,
      formatter (data) {
        return data.name + ':' + data.percent.toFixed(2) + The '%'; }}}}Copy the code

The next step is to highlight!!

We accept parameters to display the graph back and forth:

  • Table data ByYear (Get the year to display the table data)
  • Here are three examples of data to illustrate
export function tableListByYearMonth () {
  return[{prop: ' '.// 
      
        Corresponds to the attribute name 1
      
      label: ' '.// 
      
        The header label
      
      label2: ' '.// 
      
        The header label
      
      width: 60
    },
    {
      prop: ' '.// 
      
        Corresponds to the attribute name 2
      
      label: ' '.// 
      
        The header label
      
      label2: ' '.// 
      
        The header label
      
      width: 70
    },
    {
      prop: ' '.// 
      
        Corresponding attribute name 3
      
      label: ' '.// 
      
        The header label
      
      label2: ' '.// 
      
        The header label
      
      width: 70]}},Copy the code

And finally, this is where the data comes in

export function getDataByYear (that, params) {
  let monthList = [];
  let preYearSale = [];
  let curYearSale = [];
  let yearOnYear = [];
  let monthOnMonth = [];
  that.Loading = true;
  that.$store.dispatch('url', params).then((res) = > {
    that.Loading = false;
    if (res && res.data && res.code == 200) {
      let dataList = res.data;
      if(dataList.length ! =0) {
          dataList.map((item, index) = > {
            item.id = index + 1monthList.push(item.month); PreYearSale. Push (item. The parameters1? Item. The parameters1 : 0) curYearSale. Push (item parameter2) yearOnYear. Push (item parameter3! =null? Item. The parameters3 : The '-') monthOnMonth. Push (item parameter4! =null? Item. The parameters4 : The '-')});// Populate the data
      that.chartDataByYear1.xAxis[0].data = monthList;
      that.chartDataByYear1.series[0].data = preYearSale;
      that.chartDataByYear1.series[1].data = curYearSale;
      that.chartDataByYear1.series[2].data = yearOnYear;
      that.chartDataByYear1.series[3].data = monthOnMonth;
      that.$refs.barByYear1.reloadEcharts(that.chartDataByYear1); // Render the image
    } else {
      that.timeOut = true;
      that.$message.closeAll();
    }

  })
    .catch(() = > {
      that.Loading = false;
      that.timeOut = true;
    });
}
Copy the code

This completes the entire rendering

Like small partners please a triplet, pay attention to support the blogger, not regularly updated, if there is an incorrect place, please point out….