vue 3中 使用 echarts

echarts 功能很強(qiáng)大,但是要在vue3 項(xiàng)目中使用,配置卻有點(diǎn)麻煩,記錄一下在vue3中使用,以后可以直接復(fù)制代碼!

echarts 在v5之后,為了適配 各種前端框架,減少打包體積,開始采用組件化的思路組織代碼,對(duì)熟悉了之前整體一個(gè)包,引入包就能用的模式,在新模式下有點(diǎn)無從下手,現(xiàn)在開始使用:

引入依賴

pnpm add echarts vue-echarts

echarts 是 本體,vue-echarts 定義了一個(gè)Vue組件,方便在vue 代碼中使用echarts。

使用前初始化

echarts 組件化后,使用前需要初始化,加載需要的功能組件,這樣就只引入項(xiàng)目使用的組件,不會(huì)整體加載,減少了構(gòu)建包的體積。 一般在項(xiàng)目中可以單獨(dú)用一個(gè)文件來初始化加載本項(xiàng)目要用到的 echarts 組件、圖表, 因?yàn)関ue 有插件機(jī)制,可以把初始化放到一個(gè)插件中:

// echarts-init.ts

import { use } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { PieChart, LinesChart, LineChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  DatasetComponent,
} from "echarts/components";
import { THEME_KEY } from "vue-echarts";
import { type App, type Plugin } from "vue";
import VChart from "vue-echarts";

export const echartsInitPlugin: Plugin = (app: App, ...options: any[]) => {
  use([
    CanvasRenderer,
    DatasetComponent,
    PieChart,
    LinesChart,
    LineChart,
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    GridComponent,
    DataZoomComponent,
  ]);

  app.provide(THEME_KEY, "");
  // 把echart 組成到
  app.component("v-chart", VChart);
};

在程序入口使用初始化插件

//main.ts

import { useEchartsInit } from "./common/charts-init";

// 初始化echarts
app.use(echartsInitPlugin);

圖表組件

<template>
    <div>
        <v-chart class="chart" :option="chartOptions" />
    </div>
</template>

<script setup lang="ts">

import { onMounted, reactive } from "vue";
import { curl, type IRes } from "@/common/http";

const aDay = 1000 * 60 * 60 * 24;

interface RecordRow {
    created: string,
    count: number,
    kind: number,
    trend: number,
    [key: string]: any,
}

const chartOptions = reactive({
    tooltip: {
        trigger: 'axis',
        valueFormatter: function (value: string | number) {
            return typeof value == 'number' ? value.toFixed(2) : value;
        }
    },
    dataset: {
        dimensions: ['created', 'count', 'kind', 'trend'],
        source: [] as any[]
    },
    title: {
        left: 'center',
        text: '天然氣用量'
    },

    xAxis: {
        type: 'time',
        axisLabel: {
            formatter: "{yy}-{MM}-{dd} {HH}:{mm}",
        },

        // boundaryGap: false
    },
    yAxis: [
        {
            type: 'value',
            axisLine: {
                show: true,
            },
            name: "數(shù)量",
            splitLine: {
                show: true,
            },
            boundaryGap: [0, '100%']
        },
        {
            type: 'value',
            name: '趨勢(shì)(每天)',
            axisLine: {
                show: true,
            },
            boundaryGap: [0, '100%'],
            splitLine: {
                show: false,
                lineStyle: {
                    color: ["#4E88E6"]
                }
            },

        }
    ],
    dataZoom: [
        {
            type: 'inside',
            start: 0,
            end: 100
        },
        {
            start: 0,
            end: 100
        }
    ],
    series: [
        {
            name: '天然氣用量',
            type: 'line',
            symbol: 'pin',
            symbolSize: 20,
            yAxisIndex: 0,
            label: {
                show: true,
            },
            encode: {
                x: 'created',
                y: 'count'
            }
        },
        {
            name: '用氣趨勢(shì)',
            type: 'line',
            symbol: 'pin',
            symbolSize: 20,
            yAxisIndex: 1,
            label: {
                show: true,
                formatter: function ({ value }: { value: RecordRow }) {
                    return value.trend.toFixed(2)
                }
            },
            encode: {
                x: 'created',
                y: 'trend'
            }
        }
    ]

});

onMounted(() => {

    curl.get<IRes<any[]>>('/expend/gas').subscribe(res => {
        console.log(res)
        if (res.code == 200) {
            // @ts-nocheck
            chartOptions.dataset.source = res.data.map((item, index, arr) => {
                let trend = 0;
                if (index !== 0) {
                    let diff = item.count - arr[index - 1].count;
                    let span = (new Date(item.created).getTime() - new Date(arr[index - 1].created).getTime()) / aDay
                    trend = diff / span;
                }

                return {
                    ...item,
                    trend
                }
            }) as any[]
        }
    })

})

</script>

<style scoped>
.chart {
    height: 400px;
}
</style>

效果如下:

image.png

最后

echarts 的配置
echarts 示例
echarts 文檔

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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