1,使用npm 或者 yarn 下载 echarts
2,当前页面导入
import * as echarts from "echarts";
3,定义容器
<template>
<div class="contain">
<div id="chart" ref="container"></div>
</div>
</template>
需要用 ref 获取dom
import { ref, onMounted } from "vue";
const container = ref();
let myChart=ref()
//防止初次第一个页面不渲染
onMounted(() => {
initEcharts();
});
const initEcharts = () => {
if (myChart.value != null && myChart.value != "" && myChart.value != undefined) {
myChart.value.dispose();
}
myChart.value = echarts.init(container.value);
// 绘制图表
myChart.value.setOption({
title: {
text: "本月商业险和非车实际达成趋势图",
},
tooltip: {
trigger: "axis",
axisPointer: { type: "cross" },
},
legend: {
data: ["净保费金额", "非车金额", "商业险单量", "非车单量"],
},
xAxis: {
type: "category",
axisLabel: { interval: 0, rotate: 40, color: "#fa3534", fontSize: 14 },
data: [
"2023/10/1",
"2023/10/2",
"2023/10/3",
"2023/10/4",
"2023/10/5",
"2023/10/6",
"2023/10/7",
"2023/10/8",
"2023/10/9",
"2023/10/10",
"2023/10/11",
"2023/10/12",
"2023/10/13",
"2023/10/14",
],
},
yAxis: [
{
type: "value",
name: "",
min: 0,
max: 100000,
position: "left",
},
{
type: "value",
name: "",
min: 0,
max: 35,
position: "right",
},
],
series: [
{
name: "净保费金额",
type: "bar",
yAxisIndex: 0,
data: [
1470.92,
3728.34,
4371.74,
17682.26,
34951.48,
90901.49,
56780.49,
33247.49,
37431.93,
35465.66,
46364.19,
47395.3,
26142.39,
47354.11,
],
},
{
name: "非车金额",
type: "bar",
itemStyle: {
color: "#67C23A",
},
yAxisIndex: 0,
data: [
200,
6400,
3100,
680,
1390,
2240,
1420,
1500,
950,
680,
1600,
1700,
3600,
1890,
],
},
{
name: "非车单量",
type: "line",
itemStyle: {
color: "#FFD700",
},
yAxisIndex: 1,
data: [1, 3, 15, 6, 8.9, 10.9, 9, 6.2, 12.5, 15.2, 7.2, 32, 6.9, 11.9],
},
{
name: "商业险单量",
type: "line",
itemStyle: {
color: "#9400D3",
},
yAxisIndex: 1,
data: [6, 7, 15, 6, 8.9, 12, 9, 16, 12.5, 17, 7.2, 18, 1, 11.9],
},
],
});
};
defineExpose({ initEcharts });
这里我用了el-tabs 组件,父组件调用子组件的方法 initEcharts
<el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleChange">
<el-tab-pane label="趋势图" name="first"><Trend ref="trendChild" /></el-tab-pane>
<el-tab-pane label="666" name="second"><Wrend ref="wrendChild" /></el-tab-pane>
</el-tabs>
const handleChange = (tab, event) => {
if (tab.props.name == "first") {
/* trendChild.value.initEcharts(); */
setTimeout(()=>{
trendChild.value.initEcharts();
},100)
} else if (tab.props.name == "second") {
wrendChild.value.initEcharts();
/* setTimeout(()=>{
wrendChild.value.initEcharts();
},100) */
}
};
这里要使用延时器, 浏览器刷新后,页面是需要重新加载渲染,而在加载还未完成时,echarts图函数被已加载,页面还没渲染结束,肯定就获取不到DOM的宽高啦
然后就是在用echart做表格自适应的时候,每次 resize 都会出现echart警告,虽然不影响echart的展示。
解决办法
if (myChart.value != null && myChart.value != "" && myChart.value != undefined) {
myChart.value.dispose();
}
这是我最近用vue3使用echarts,希望能帮到大家