ECharts:一个基于 JavaScript 的开源可视化图表库。
目录
效果
一、介绍
1、官方文档:Apache ECharts
2、官方示例
事件与行为 - 概念篇 - 使用手册 - Apache ECharts
二、准备工作
1、安装依赖包
npm install echarts --save
2、示例版本
"echarts": "^5.4.2",
三、使用步骤
1、在单页面引入 ' echarts '
import * as echarts from "echarts";
注:上面的代码会引入 ECharts 中所有的图表和组件,如果你不想引入所有组件,也可以使用 ECharts 提供的按需引入的接口来打包必须的组件。详见官方文档:在项目中引入 ECharts - 入门篇 - Handbook - Apache ECharts
2、指定容器并设置容器宽高
<template>
<div id="main"></div>
</template>
<script setup lang="ts">
import * as echarts from "echarts";
const trendsTooltip = ref();
initChart() {
let chartDom = document.getElementById("main");
let myChart = echarts.init(chartDom);
let option;
...详见完整示例
};
</script>
<style scoped>
#main {
width: 1000px;
height: 500px;
}
</style>
3、数据处理(关键点)
1)依次高亮图形
// 动态显示tootip
// 当前高亮图形所在下标
let currentIndex= -1;
// 取消之前高亮的图形
trendsTooltip.value = setInterval(function () {
let dataLen = option.series[0].data.length;
myChart.dispatchAction({
type: 'downplay',
seriesIndex: 0,
dataIndex: currentIndex,
});
// 当前高亮图形
currentIndex= (currentIndex+ 1) % dataLen;
myChart.dispatchAction({
type: 'highlight',
seriesIndex: 0,
dataIndex: currentIndex,
});
// 显示 tooltip
// tootip每隔三秒依次显示
myChart.dispatchAction({
type: 'showTip', // 根据 tooltip 的配置项显示提示框。
seriesIndex: 0,
dataIndex: currentIndex,
});
if (currentIndex>= option.series[0].data.length) {
currentIndex= 0;
}
}, 3000);
2)页面销毁前清除定时器,避免占用内存而造成内存泄漏
onUnmounted(() => {
clearInterval(trendsTooltip.value);
});
四、完整示例
<template>
<div id="main"></div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import * as echarts from "echarts";
initChart() {
let chartDom = document.getElementById("main");
let myChart = echarts.init(chartDom);
let option;
option = {
tooltip: {
trigger: 'item',
confine: true,
},
grid: {
top: 10,
bottom: 30,
},
legend: false,
series: [
{
type: 'pie',
radius: '50%',
data: [
{ value: 1048, name: '未开工' },
{ value: 735, name: '进行中' },
{ value: 580, name: '已完工' },
,
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)',
},
},
},
],
};
option && myChart.setOption(option);
// 动态显示tootip
// 当前高亮图形所在下标
let currentIndex= -1;
// 取消之前高亮的图形
trendsTooltip.value = setInterval(function () {
let dataLen = option.series[0].data.length;
myChart.dispatchAction({
type: 'downplay',
seriesIndex: 0,
dataIndex: currentIndex,
});
// 当前高亮图形
currentIndex= (currentIndex+ 1) % dataLen;
myChart.dispatchAction({
type: 'highlight',
seriesIndex: 0,
dataIndex: currentIndex,
});
// 显示 tooltip
// tootip每隔三秒依次显示
myChart.dispatchAction({
type: 'showTip', // 根据 tooltip 的配置项显示提示框。
seriesIndex: 0,
dataIndex: currentIndex,
});
if (currentIndex>= option.series[0].data.length) {
currentIndex= 0;
}
}, 3000);
};
onMounted(() => {
initChart();
}
onUnmounted(() => {
clearInterval(trendsTooltip.value);
});
</script>
<style scoped>
#main {
width: 1000px;
height: 500px;
}
</style>