简介
项目中使用的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}, {b},{c},{d},{e},分别表示系列名,数据名,数据值等
// 饼图、仪表盘、漏斗图: {a}(系列名称),{b}(数据项名称),{c}(数值), {d}(百分比)
formatter: "{b}: {c} ({d}%)"
},
series: [{
name: "",
type: "pie",
radius: ["20%", "30%"],
label: {
formatter: " {per|{d}%} {b|{b}} ",
rich: {
b: {
color: "#fff",
fontSize: 16,
lineHeight: 33
},
per: {
padding: [2, 4],
borderRadius: 2
}
}
},
data: [{
value:30,
name: "win8",
itemStyle: {
normal: {
color: "#02B672"
}
} //设置圆环的颜色
},
{
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,如运行报错可先下载相关依赖,关注我持续更新