vue3 中echart使用

全局引用

推荐使用 provide 和 inject

第一步在main.js中引入echarts

省去安装 echarts (yarn add echarts)
import * as echarts from 'echarts'
const app = createApp(App)
app.provide('$echarts', echarts)
app.use(router).use(ElementPlus).mount('#app')

第二步,在使用页面中注入 $echarts

import { defineComponent, onMounted, inject, ref, reactive, toRefs, watch } from 'vue'

...
 const curEchart = inject('$echarts')
...

具体参考列子
主语:DOM 中声明的ref 要与 setup 中声明的保持一直

<template>
<div class="bar-echarts">
  <div class="baseBarEcharts" ref="baseBarEcharts"></div>
  <div class="baseBarEcharts" ref="baseBarEchartsSecondRef"></div>
  <div class="baseBarEcharts" ref="pieRef"></div>
  <!-- <div class="baseBarEcharts" ref="pieSecondRef"></div> -->
</div>
</template>

<script>
import { defineComponent, onMounted, inject, ref, reactive, toRefs, watch } from 'vue'
import myHttp from "@/https/index.js"

export default defineComponent({
  name: 'BarEchasrts',
  setup() {
  	// return 出去的确保与DOM结构中一致
    const baseBarEcharts = ref(null)
    const baseBarEchartsSecondRef = ref(null)
    const pieRef = ref(null)
    // 注入echarts
    const curEchart = inject('$echarts')
   
    const initEchart = () =>{
      const myEChart = curEchart.init(baseBarEcharts.value);
      const baseBarEchartsSecond = curEchart.init(baseBarEchartsSecondRef.value);
      const { echartData } = myEchartRea
      const option = {
        xAxis: {
          data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
        },
        legend: {
          data: ['年龄', '性别']
        },
        yAxis: {
          name: '',
          type: 'value'
        },
        series: [
          {
            name: '年龄',
            type: "bar",
            prop: 'age',
            data: [23, 24, 18, 25, 27, 28, 25],
          },
          {
            name: '性别',
            type: "line",
            prop: 'age',
            data: [23, 24, 18, 25, 27, 28, 25],
          }
        ].map(item => {
          item.data = echartData && echartData.length && echartData.map(itm => {
            return itm[item['prop']] || 0
          })
          return item
        }),
      }

      option.xAxis.data = echartData && echartData.length && echartData.map(itm => {
        return itm.name
      }) || []

      console.log('=option==:', option)

      myEChart.setOption(option);
      baseBarEchartsSecond.setOption(option);
      // 根据页面大小自动响应图表大小
      window.addEventListener("resize", function () {
        myEChart.resize();
        baseBarEchartsSecond.resize();
      });
    }
    const initEchartPie = () =>{
      const myEChart= curEchart.init(pieRef.value);
      const { echartData } = myEchartRea
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          data: ['男', '女']
        },
        series: [
          {
            name: '男',
            radius: '50%',
            type: "pie",
            prop: 'age',
            data: [23, 24, 18, 25, 27, 28, 25],
          }
         
        ].map(item => {
          item.data = echartData && echartData.length && echartData.map(itm => {
            return {
              value:itm[item['prop']] || 0,
              name: itm.date
            }
          })
          return item
        }),
      }


      console.log('=option==:', option)

      myEChart.setOption(option);
      // 根据页面大小自动响应图表大小
      window.addEventListener("resize", function () {
        myEChart.resize();
      });
    }


    const myEchartRea = reactive({
      echartData: [],
      getEchartData() {
      // 本地node服务以及 moke数据
        myHttp.get('/api/mode/echartLists').then(res => {
          console.log('===getEchartData res=:', res)
          if (res.data.status === 200) {
            myEchartRea.echartData = res.data.data.echartsMokck || []
          }
        })
      }
    })

    onMounted(() => {
      myEchartRea.getEchartData()
      // initEchart();
      // initbaseBarEchartsSecond();
    })
    watch(() => myEchartRea.echartData, (n, o) => {
      if (n && n.length) {
        initEchart();
        initEchartPie()
      }
    }, {deep: true, immediate: true})
    

    return {
      baseBarEcharts,
      baseBarEchartsSecondRef,
      pieRef,
      ...toRefs(myEchartRea)
    }
  }
  
})
</script>

<style lang='scss' scoped>

效果如下图
vue3 中echart使用_第1张图片

你可能感兴趣的:(vue3,echarts,javascript,vue.js)