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