1. 安装 echarts
安装 echarts 用 npm install 就可以了。
npm install echarts
要是下载很慢,可以使用 cnpm 来安装。
npm install -g cnpm --registry=https://registry.npm.taobao.org
cnpm install echarts
2. 在 Vue 文件中创建图表
创建图表的代码比较简单。
<template>
<div :id="id" :class="className" :style="{ height:height, width:width }" />
</template>
<script>
import echarts from "echarts";
export default {
name: "StockPieChart",
props: {
className: {
type: String,
default: "chart"
},
id: {
type: String,
default: "chart"
},
width: {
type: String,
default: "200px"
},
height: {
type: String,
default: "200px"
}
},
data() {
return {
chart: null
};
},
mounted() {
// 1. 创建图表实例
this.chart = echarts.init(document.getElementById(this.id));
// 2. 设置图表基本配置
this.initChart();
// 3.获取图表数据并填入图表
this.setChartData();
},
beforeDestroy() {
if (!this.chart) {
return;
}
// 组件销毁前,回收图表
this.chart.dispose();
this.chart = null;
},
methods: {
initChart() {
this.chart.setOption({
tooltip: {
trigger: "item",
formatter: "{a} <br/>{b}: {c} ( {d}% )"
},
legend: {
orient: "vertical",
left: 10,
data: [
"已分配库存",
"冻结库存",
"未上架库存",
"其他区域库存",
"正常库位库存"
]
},
series: [
{
name: "库存状态",
type: "pie",
radius: ["40%", "80%"],
avoidLabelOverlap: false,
label: {
show: false,
position: "center"
},
emphasis: {
label: {
show: true,
fontSize: "10",
fontWeight: "bold"
}
},
labelLine: {
show: false
}
}
]
});
},
setChartData() {
// 模拟异步获取数据的效果
this.chart.showLoading();
setTimeout(() => {
let data = [
{ value: 335, name: "已分配库存" },
{ value: 310, name: "冻结库存" },
{ value: 234, name: "未上架库存" },
{ value: 135, name: "其他区域库存" },
{ value: 1548, name: "正常库位库存" }
];
this.chart.setOption({
series: [
{
data: data
}
]
});
this.chart.hideLoading();
}, 1000);
}
}
};
</script>
最终,上面代码的图表效果图如下:
这个图表使用的基本是默认的样式,可以根据实际需要,做进一步的配置。
比如说,换个配色,视觉效果大不一样啊!
echarts 图表的配置项超级的多,可以根据项目的实际情况来配置。