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 圖表的配置項超級的多,可以根據項目的實際情況來配置。