echarts 是百度基于 JavaScript 实现的一个开源可视化图表库,主要特点就是可视化类型丰富、动画炫酷、使用简单。
这个教程就简单演示如何在 Vue 3 项目中使用 echarts。
1、导入 echarts
import * as echarts from "echarts";
2、初始化 echarts 并设置图表实例的配置项以及数据
const state = reactive({option: {legend: {x: "center",y: "bottom",},tooltip: {trigger: "item", // axis item none三个值formatter: "{b}:{d}%",},series: [{type: "pie",radius: "50%",label: {show: true,// formatter: "{b} : {c} ({d}%)", //带当前图例名 + 百分比// formatter: "{d}%", //只要百分比formatter: "{b}:{d}%",},labelLine: { show: true },data: [{value: 1956,name: "非星级",},{value: 1866,name: "一星级",},{value: 1725,name: "二星级",},{value: 1535,name: "三星级",},{value: 1505,name: "四星级",},{value: 1414,name: "五星级",},],},],},
});
const initeCharts = () => {let myChart = echarts.init(document.getElementById("myChart"));// 绘制图表myChart.setOption(state.option);
};
onMounted(() => {initeCharts();
});
3、设置接收容器
<template><div><div id="myChart" style="width: 500px; height: 500px"></div></div>
</template>
完整代码
<template><div><div id="myChart" style="width: 500px; height: 500px"></div></div>
</template><script setup>
import { reactive, ref, onMounted } from "vue";
import * as echarts from "echarts";
const state = reactive({option: {legend: {x: "center",y: "bottom",},tooltip: {trigger: "item", // axis item none三个值formatter: "{b}:{d}%",},series: [{type: "pie",radius: "50%",label: {show: true,// formatter: "{b} : {c} ({d}%)", //带当前图例名 + 百分比// formatter: "{d}%", //只要百分比formatter: "{b}:{d}%",},labelLine: { show: true },data: [{value: 1956,name: "非星级",},{value: 1866,name: "一星级",},{value: 1725,name: "二星级",},{value: 1535,name: "三星级",},{value: 1505,name: "四星级",},{value: 1414,name: "五星级",},],},],},
});
const initeCharts = () => {let myChart = echarts.init(document.getElementById("myChart"));// 绘制图表myChart.setOption(state.option);
};
onMounted(() => {initeCharts();
});
</script><style lang="scss" scoped></style>