vue-echarts-配置-請求數(shù)據(jù)

1. 前言

  1. vue里面使用這個echarts是非常常見的場景
  2. 但是我發(fā)現(xiàn)很多文章都是直接給echarts寫死的數(shù)據(jù),因為都是從echarts官網(wǎng)示例直接拿過來的
  3. echarts在使用請求數(shù)據(jù)進行操作的時候還有點小坑,記錄一下吧

2. 效果預(yù)覽

  1. 習(xí)慣看著設(shè)計圖來寫
    演示.gif

3. echarts使用

  1. 安裝 npm install echarts --save
  2. 版本"echarts": "^5.3.3",
  3. 頁面引入 5x
import * as echarts from 'echarts';
// 按需引入
import * as echarts from 'echarts/lib/echarts';
  1. echarts 5x 支持按需引入
import * as echarts from 'echarts/core';
import { BarChart } from 'echarts/charts';
import { GridComponent } from 'echarts/components';
// 注意,新的接口中默認(rèn)不再包含 Canvas 渲染器,需要顯示引入,如果需要使用 SVG 渲染模式則使用 SVGRenderer
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([BarChart, GridComponent, CanvasRenderer]);

  1. echarts4x版本的引入
import echarts from 'echarts';
// 或者按需引入
import echarts from 'echarts/lib/echarts';
  1. 注意 echarts4x 和echarts5x 引入方式是不同的

4. 不同版本vue 把 echarts掛載到全局的方式

  1. 我這里選用了把這個echarts掛載到全局
  2. vue3x 掛載全局
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import * as echarts from 'echarts';
let app = createApp(App)
const prototype = app.config.globalProperties
prototype.$echarts = echarts
app.use(store).use(router).mount('#app')

  1. vue2掛載原型
import Vue from 'vue'
import * as echarts from 'echarts';
Vue.prototype.$echarts = echarts

5. vue3 頁面使用

  1. 布局很簡潔
<template>
    <div>
        <!-- 為 ECharts 準(zhǔn)備一個定義了寬高的 DOM -->
        <div id="main" style="width: 100vw;height:100vh;"></div>
    </div>
</template>

  1. js邏輯
  2. 重點是 數(shù)據(jù)請求一定要放到onMounted里面
<script setup>
import { getCurrentInstance, reactive, onMounted } from "vue"
let serverData = reactive([])
let { proxy } = getCurrentInstance()
onMounted(async () => {
    let res = await fetch("/mock/echarts").then(res => res.json())
    console.log("mock res:", res);
    let { data, title } = res.data
    serverData = {
        data,
        title
    }
    initChart()
})


const initChart = () => {
    var myChart = proxy.$echarts.init(document.getElementById('main'));
    // 指定圖表的配置項和數(shù)據(jù)
    var option = {
        title: {
            text: serverData.title.text,
            subtext: serverData.title.subtext,
            left: 'center'
        },
        tooltip: {
            trigger: 'item'
        },
        legend: {
            orient: 'vertical',
            left: 'left'
        },
        series: [
            {
                name: 'Access From',
                type: 'pie',
                radius: '50%',
                data: serverData.data,
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };
    // 使用剛指定的配置項和數(shù)據(jù)顯示圖表。
    myChart.setOption(option);
}
</script>

6. mock假數(shù)據(jù)

  1. vue.config.js
  2. 這里vue/cli 是4x版本的
  3. beforedevServer的屬性
    proxy:"",
    before(app) {
      app.get("/mock/echarts", (req, res) => {
        res.json({
          code: 1000,
          msg: "成功",
          data: {
            data:[
              { value: 1048, name: "vue" },
              { value: 735, name: "React" },
              { value: 580, name: "angular" },
              { value: 484, name: "小程序" },
              { value: 300, name: "uniApp" },
            ],
            title:{
              text:'前端占比',
              subtext:'演示著玩'
            }
          },
        });
      });
    },

7. vue2 中使用方式

  1. 布局都一樣
<template>
    <div>
        <!-- 為 ECharts 準(zhǔn)備一個定義了寬高的 DOM -->
        <div id="main" style="width: 100vw;height:100vh;"></div>
    </div>
</template>
<script>

  1. 沒用setup語法糖
  2. 也沒用全局掛載 echarts
  3. 直接上邏輯代碼
  4. 一般會data聲明個echarts,方便在頁面消失的時候銷毀 echarts
  5. 數(shù)據(jù)請求一定要寫在mounted里面,寫到created里面無效
<script>
import * as echarts from 'echarts';
export default {
    data() {
        return {
            echarts:null,
            serverData: {
                text: '標(biāo)題',
                data: []
            }
        }
    },
    beforeDestroy() {
        if (!this.chart) {
            return
        }
        this.chart.dispose()
        this.chart = null
    },
    async mounted() {
        let res = await fetch("/mock/echarts").then(res => res.json())
        console.log("mock res:", res);
        let { data, title } = res.data
        this.serverData = {
            data,
            title
        }
        this.initChart()

    },
    methods: {
        initChart() {
            var myChart = this.echarts.init(document.getElementById('main'));
            // 指定圖表的配置項和數(shù)據(jù)
            var option = {
                title: {
                    text: this.serverData.title.text,
                    subtext: this.serverData.title.subtext,
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left'
                },
                series: [
                    {
                        name: 'sss',
                        type: 'pie',
                        radius: '50%',
                        data: this.serverData.data,
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            };
            // 使用剛指定的配置項和數(shù)據(jù)顯示圖表。
            myChart.setOption(option);
        }
    }

}
</script>

8. 后記

  1. vue/cli 不同版本配置mock
  2. 熟能生巧
  3. 這個單獨封裝echarts 圖表組件也行,寬高,樣式,id等等都可以作為屬性傳進來.方便自定義

參考資料

echarts官網(wǎng)示例
vue3如何掛載全局組件


初心

我所有的文章都只是基于入門,初步的了解;是自己的知識體系梳理,如有錯誤,道友們一起溝通交流;
如果能幫助到有緣人,非常的榮幸,一切為了部落的崛起;
共勉
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容