SoFunction
Updated on 2025-04-12

Two ways to introduce echart and precautions for vue3

After creating a vue3 project, install echarts

Terminal input:

npm i echarts --save

After installation:

1. Reference echarts directly in the component

<script setup>
        import * as echarts from 'echarts'  
</script>

2. Global introduction, generally

(Usage of provide and inject)

<script setup>
        import * as echarts from 'echarts'  
        provide('echarts',echarts)
</script>

Get it with inject in component that needs to be used with echarts

<script setup>
        const echarts  = inject('echarts')
</script>

Notice! ! ! The chronological order of vue mount, echarts rendering, and data acquisition

1. Let’s talk about vue mount and echarts rendering first

Take the example of the introduction to the online website. (vue3 version)

&lt;script setup&gt;
import * as echarts from 'echarts';
const myCharts = ref(null)
// Initialize the echarts instance based on the prepared domvar myChart = ();
// Draw a chart({
  title: {
    text: 'Edit for ECharts'
  },
  tooltip: {},
  xAxis: {
    data: ['shirt', 'Cardwear', 'Chiffon shirt', 'Pants', 'High heel', 'sock']
  },
  yAxis: {},
  series: [
    {
      name: 'Sales',
      type: 'bar',
      data: [5, 20, 36, 10, 10, 20]
    }
  ]
});
&lt;script&gt;

At first I wrote this, and it seems that there is no problem when I open it. But as soon as you open the page, you will find that the data has not been rendered. Because vue has not been mounted to the dom element at this time, the dom element cannot be obtained, and the data cannot be rendered.

It needs to be written like this, put the action of obtaining dom elements and initializing myecharts into onMounted(()=>{})

&lt;script setup&gt;
import * as echarts from 'echarts';
onMounted(()=&gt;{
const myCharts = ref(null)
// Initialize the echarts instance based on the prepared domvar myChart = ();
// Draw a chart({
  title: {
    text: 'Edit for ECharts'
  },
  tooltip: {},
  xAxis: {
    data: ['shirt', 'Cardwear', 'Chiffon shirt', 'Pants', 'High heel', 'sock']
  },
  yAxis: {},
  series: [
    {
      name: 'Sales',
      type: 'bar',
      data: [5, 20, 36, 10, 10, 20]
    }
  ]
});
})
&lt;script&gt;

vue3: You can access the component's lifecycle hook by prefixing the lifecycle hook.

I added a setup to <script setup>, which is equivalent to being inside the setup.

The following table contains how to call the lifecycle hook inside setup():

Optional API Hook inside setup
beforeCreate Not needed*
created Not needed*
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeUnmount onBeforeUnmount
unmounted onUnmounted
errorCaptured onErrorCaptured
renderTracked onRenderTracked
renderTriggered onRenderTriggered
activated onActivated
deactivated onDeactivated

TIP:

Because setup runs around beforeCreate and created lifecycle hooks, they don't need to be explicitly defined. In other words, any code written in these hooks should be written directly in the setup function.

These functions accept a callback function, which will be executed when the hook is called by the component:

// 
 
export default {
  setup() {
    // mounted
    onMounted(() => {
      ('Component is mounted!')
    })
  }
}

Rendering and data acquisition

Get the data through axios and then render to the page through echarts

If you are using asynchronous requests, you should pay great attention!

Let me briefly introduce asynchronous requests: asynchronous requests will not affect the execution of subsequent programs during execution, for example, a child thread is opened in the main thread.

If the data is obtained asynchronously and is still being retrieved, echart has rendered the dom element, but the data requested by i has not been returned yet, and the empty data is rendered at this time.

Therefore, using asynchronous requests, you can put echart rendering and initialization into (), so that rendering empty data will not occur.

As follows:

&lt;script setup&gt;
import api from '@/api/index'
var keydata = []
var valuedata = []
const resdata = []
const wordsChartsBox = ref(null)
const echarts = inject('echarts')
function getf() {
    ('/backstage').then(res =&gt; {
        for (const key in ) {
            var element = [key]
            if (key == 1) {
                keydata = element
            } else {
                valuedata = element
            }
        }
        for (let index = 0; index &lt; ; index++) {
            (
                {
                    value: parseInt(valuedata[index]),
                    name: keydata[index]
                }
            )
        }
        const wordsChartsOption = {
            title: {
                text: 'Common Word Statistics',
                subtext: 'Statistical analysis of blind people',
                left: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a} &lt;br/&gt;{b} : {c} ({d}%)'
            },
            legend: {
                type: 'scroll',
                orient: 'vertical',
                right: 10,
                top: 20,
                bottom: 20,
                data: keydata
            },
            series: [
                {
                    name: 'Name',
                    type: 'pie',
                    radius: '55%',
                    center: ['40%', '50%'],
                    data: resdata,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        }
        const wordsCharts = ()
        (wordsChartsOption)
    })
    (resdata)
}
onMounted(() =&gt; {
    getf()
})
&lt;/script&gt;

The above is personal experience. I hope you can give you a reference and I hope you can support me more.