Echarts is used in Vue to encapsulate it as a public component (simple copy and paste)

Encapsulating Echarts components in Vue

  • premise
  • Go straight

1
This article uses Vue3 code to demonstrate the same principle as Vue2

Premise

Chinese official website: https://echarts.apache.org/zh/index.html

npm install Echarts

npm install echarts
or
pnpm install echarts
or
yarn add echarts

Get straight to the point

  1. Create the Echarts.vue file with the following code

    <template>
      <div :id="id" :style="{ height, width }" />
    </template>
    <script setup>
    import * as echarts from "echarts";
    
    let myChart = ref(null);
    
    const props = defineProps({<!-- -->
      // Differentiate charts
      id: {<!-- -->
        type: String,
        default: 'e-chart',
        required: true
      },
      // echarts canvas width and height
      width: {<!-- -->
        type: String,
        default: '100%',
      },
      height: {<!-- -->
        type: String,
        default: '300px',
      },
      // echarts loading
      loading: {<!-- -->
        type: Boolean,
        default: true,
      },
      // echarts needs options and other configurations
      fullOptions: {<!-- -->
        type: Object,
        default: () => ({<!-- -->}),
        required: true
      },
    
    })
    
    
    //redraw chart function
    const resizeHandler = () => {<!-- -->
      myChart.value.resize();
    }
    //Set anti-shake to ensure that no matter the size of the dragged window, the method of obtaining the browser width and height is only executed once
    const debounce = (fun, delay) => {<!-- -->
      let timer;
      return function () {<!-- -->
        if (timer) {<!-- -->
          clearTimeout(timer);
        }
        timer = setTimeout(() => {<!-- -->
          fun();
        }, delay);
      }
    };
    const cancalDebounce = debounce(resizeHandler, 50);
    
    
    //Listen to changes in chart data and re-render the chart
    watch(() => [props.fullOptions.options, props.loading], () => {<!-- -->
      if (!props.loading) {<!-- -->
        myChart.value.hideLoading();
        myChart.value.setOption(props.fullOptions.options, true);
        nextTick(() => {<!-- -->
          cancelDebounce()
        })
      }
    }, {<!-- --> deep: true })
    
    
    //The page is rendered successfully and the chart starts to be drawn.
    onMounted(() => {<!-- -->
      //Configure in svg format to prevent blurring problems caused by page scaling; it is recommended to use Canvas when the chart is too complex
      myChart.value = echarts.init(document.getElementById(props.id), {<!-- --> renderer: 'svg' })
      //Load icon
      myChart.value.showLoading({<!-- -->
        text: '',
        color: '#409eff',
        textColor: '#000',
        maskColor: 'rgba(255, 255, 255, .95)',
        zlevel: 0,
        lineWidth: 2,
      });
      if (!props.loading) {<!-- -->
        myChart.value.hideLoading();
        myChart.value.setOption(props.fullOptions.options, true);
      }
      //Change the chart size when adapting to different screens
      window.addEventListener('resize', cancalDebounce);
    })
    //Before the page is destroyed, destroy events and instances
    onBeforeUnmount(() => {<!-- -->
      window.removeEventListener('resize', cancelDebounce)
      myChart.value.dispose()
    })
    
    </script>
    
  2. Add echarts’ options configuration file optionsConfig.js, the code is as follows

    export const chartOptions = {<!-- -->
    // It is recommended to name it with setXXXOption
    setDemoOption(data) {<!-- -->
            let color = ['#0E7CE2', '#FF8352', '#E271DE', '#F8456B', '#00FFFF', '#4AEAB0']
    let echartData = [
    {<!-- -->
    name: 'Hardhat Wear Alarm',
    value: '13'
    },
    {<!-- -->
    name: 'Alarm for illegal intrusion',
    value: '33'
    },
    {<!-- -->
    name: 'Category C',
    value: '13'
    },
    {<!-- -->
    name: 'Category D',
    value: '13'
    }
    ]
    \t
    let formatNumber = function (num) {<!-- -->
    let reg = /(?=(\B)(\d{3}) + $)/g
    return num.toString().replace(reg, ',')
    }
    \t
    const option = {<!-- -->
    color: color,
    // tooltip: {<!-- -->
    // trigger: 'item'
    // },
    legend: {<!-- -->
    orientation: 'vertical',
    icon: 'rect',
    x: '5%',
    y: 'center',
    itemWidth: 12,
    itemHeight: 12,
    align: 'left',
    textStyle: {<!-- -->
    rich: {<!-- -->
    name: {<!-- -->
    fontSize: 12,
    color: 'rgba(255, 255, 255, 0.7)'
    },
    value: {<!-- -->
    fontSize: 16,
    padding: [0, 5, 0, 5],
    color: 'rgba(255, 255, 255, 0.7)'
    },
    unit: {<!-- -->
    fontSize: 12
    }
    }
    },
    formatter: function (name) {<!-- -->
    let res = echartData.filter((v) => v.name === name)
    res = res[0] || {<!-- -->}
    let unit = res.unit || ''
    // return '{name|' + name + '} {value|' + res.value + '}{unit|' + unit + '}'
    return '{name|' + name + '} '
    },
    data: echartData
    },
    series: [
    {<!-- -->
    type: 'pie',
    radius: ['20%', '40%'],
    center: ['65%', '60%'],
    color,
    data: echartData.map((item, index) => {<!-- -->
    return {<!-- -->
    label: {<!-- -->
    color: color[index]
    },
    ...item
    }
    }),
    hoverAnimation: false,
    itemStyle: {<!-- -->
    borderWidth: 2
    },
    labelLine: {<!-- -->
    show: true,
    length: 30,
    length2: 60,
    lineStyle: {<!-- -->
    color: '#0080ff'
    }
    },
    label: {<!-- -->
    show: true,
    formatter: (params) => {<!-- -->
    return '{icon|●}{name|' + params.name + '}{value|' + formatNumber(params.value) + '}'
    },
    padding: [0, -80, 25, -100],
    rich: {<!-- -->
    icon: {<!-- -->
    fontSize: 16
    },
    name: {<!-- -->
    fontSize: 12,
    padding: [0, 10, 0, 4]
    },
    value: {<!-- -->
    fontSize: 12,
    fontWeight: 'bold'
    }
    }
    }
    }
    ]
    }
    return option
    },
    
    }
    
  3. Introduce the Echarts component into the Vue view. The code example is as follows

    <ECharts id="demoEcharts" width="500px" height="500px" :full-options="echartsOptions" :loading="loading"></ECharts>
    
    //Introduce echarts’ options configuration file optionsConfig.js
    import {<!-- --> chartOptions } from '@/components/ECharts/optionsConfig.js'
    
    //Define loading and echarts configuration items
    const loading = ref(true)
    const echartsOptions = reactive({<!-- -->
      options:{<!-- -->}
    })
    
    // Simulate asynchronous
    setTimeout(() => {<!-- -->
      loading.value = false
      echartsOptions.options = chartOptions.setDemoOption();
    },500)
    

That’s the end here. There will be updates related to the front-end series in the future, so please continue to pay attention!
Thanks for reading. If there are any mistakes, please leave a message in the comment area below! ! !

111

Related articles
chart set
Using echarts in Vue2 projects