簡介
項目中使用的echart圖形有多個青团,而多次引入編寫導致代碼大量冗余何什,此時最好的解決方式就是封裝组哩。
具體操作如下
前期需要下載安裝依賴
可參考相關文檔
封裝組件
<template>
<!-- echart子組件 -->
<div class="bar">
<div :id="id" class="bar_canvas"></div>
</div>
</template>
<script>
import echarts from 'echarts'
export default {
name: "eachrtUtils",
props: ["propData", "id"],
data() {
return {
myChart: null
};
},
mounted() {
if (this.id) {
let myChart = echarts.init(document.getElementById(this.id));
this.myChart = myChart;
this.myChart.setOption(this.propData);
}
}
}
</script>
<style lang="less" scoped>
.bar {
width: 100%;
height: 100%;
position: absolute;
.bar_canvas {
width: 100%;
height: 100%;
}
}
</style>
使用組件
<template>
<!-- 復用組件——示例(顯示成功) -->
<div>
<div class="bar">
<eachrtUtils :propData="dataArr" id="canvans" class="bar_canvas"></eachrtUtils>
</div>
<div class="bar1">
<eachrtUtils :propData="option" id="can_view" class="bar_canvas1"></eachrtUtils>
</div>
</div>
</template>
<script>
import eachrtUtils from './eachrtUtils'
export default {
components: {
eachrtUtils
},
data() {
return {
myChart: null,
option: {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line'
}]
},
dataArr: {
tooltip: {
trigger: "item",
//字符串模板, 模板變量有 {a}, 处渣,{c}伶贰,bzd0vbe,{e}罐栈,分別表示系列名黍衙,數(shù)據(jù)名,數(shù)據(jù)值等
// 餅圖荠诬、儀表盤们豌、漏斗圖: {a}(系列名稱),浅妆(數(shù)據(jù)項名稱)望迎,{c}(數(shù)值), ytubbog(百分比)
formatter: ": {c} (hgg5ue0%)"
},
series: [{
name: "",
type: "pie",
radius: ["20%", "30%"],
label: {
formatter: " {per|7zhsl0g%} {b|凌外} ",
rich: {
b: {
color: "#fff",
fontSize: 16,
lineHeight: 33
},
per: {
padding: [2, 4],
borderRadius: 2
}
}
},
data: [{
value:30,
name: "win8",
itemStyle: {
normal: {
color: "#02B672"
}
} //設置圓環(huán)的顏色
},
{
value: 20,
name: "win10",
itemStyle: {
normal: {
color: "#0FC2E7"
}
}
},
{
value: 20,
name: "winXP",
itemStyle: {
normal: {
color: "#0C6CE8"
}
}
},
{
value: 20,
name: "macOS",
itemStyle: {
normal: {
color: "#DF4546"
}
}
},
{
value: 20,
name: "win7",
itemStyle: {
normal: {
color: "#F7BB2D"
}
}
}
]
}]
},
};
}
};
</script>
<style lang="less">
.bar {
width: 500px;
height: 500px;
position: absolute;
top: 0;
right: 0;
// background-color: #2C3E50;
}
.bar1 {
width: 500px;
height: 500px;
position: absolute;
top: 0;
left: 0;
}
.bar_canvas {
width: 100%;
height: 100%;
}
</style>
效果圖
效果
特別提醒
此項目中使用了ElementUI,less辩尊,如運行報錯可先下載相關依賴,關注我持續(xù)更新