<template>
<div class="chart_container">
<div :id="id" class="chartPie"></div>
</div>
</template>
<script>
// 生成一个 id 值给标签,目的是为了当多次使用组件防止id重复
const uid = function () {
return new Date().getTime()
}
import { getAction } from '@/api/manage'
export default {
name: 'HomeEcharts',
props: {
echartsItem: {
required: true,
default: () => {},
},
},
components: {},
data() {
return {
// 图表id
id: null,
// 图表实例
chartPie: null,
url: {
echartsUrl: '',
},
}
},
created() {
// 生成一个 id 值给标签,目的是为了当多次使用组件防止id重复
this.id = uid()
// 获取图表数据Url
this.url.echartsUrl = this.echartsItem.urlAddress
},
mounted() {
this.initData()
this.drawCharts()
},
methods: {
drawPieChart() {
// 创建echarts图表实例
// devicePixelRatio canvas像素比,提高清晰度
let chartPie = this.$echarts.init(document.getElementById(this.id), null, { devicePixelRatio: 2.5 })
// 图表自适应
window.addEventListener('resize', () => {
chartPie.resize()
})
chartPie.setOption({
tooltip: {
trigger: 'item',
// 显示百分比
// formatter: '{a} <br/>{b} : {c} ({d}%)',
},
//分类条形符
legend: {
orient: 'vertical',
// 位置
x: 'right',
y: 'center',
//图案大小
itemHeight: 15,
itemWidth: 13,
// 间距大小
itemGap: 10,
},
//饼状图类型以及数据源
series: [
{
type: 'pie',
// 饼图大小
radius: '70%',
// 防止标签重叠
avoidLabelOverlap: true,
// label显示在饼图里面
label: {
position: 'inside',
fontSize: 11,
// 格式化要显示的内容
formatter: '{c}',
},
// 去掉折线
labelLine: {
show: false,
},
// 饼图位置
center: ['37%', '45%'],
// 数据源
data: [],
//设置饼状图扇形区域的样式
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)',
},
},
},
],
})
this.chartPie = chartPie
},
//动态获取饼状图的数据
async initData() {
this.load()
if (!this.url.echartsUrl) {
this.$message.error('请检查报表地址是否存在')
} else {
getAction(this.url.echartsUrl).then((res) => {
if (res.success) {
this.hideLoad()
const data = res.result
// 注入数据
this.chartPie.setOption({
series: [
{
data: data,
},
],
})
} else {
this.$message.error(res.message)
this.hideLoad()
}
})
}
},
//调用 showLoading 方法显示
load() {
let myChart = this.$echarts.init(document.getElementById(this.id))
myChart.showLoading({
text: '数据加载中...',
maskColor: 'rgba(255, 255, 255, 1)', //加载的背景颜色
zlevel: 0,
})
},
//调用 hideLoading 方法隐藏加载动画。
hideLoad() {
let myChart = this.$echarts.init(document.getElementById(this.id))
myChart.hideLoading()
},
// 调用 绘制图表
drawCharts() {
this.drawPieChart()
},
},
watch: {},
}
</script>
<style lang="less" scoped>
.chart_container {
width: 100%;
height: calc(100% - 26px);
.chartPie {
width: 100%;
height: 100%;
}
}
</style>
记录一下用echarts写的饼图,echarts封装成vue组件,并且自适应屏幕大小,防止以后再写的时候还要去百度
最新推荐文章于 2024-07-05 11:10:29 发布