一、完整代码
<template>
<div>
<div id="main1" ref="main1"></div>
</div>
</template>
<script>
import * as echarts from 'echarts';
import { mapState } from 'vuex';
export default {
name: 'PieChart',
props: {
bedtype: {
type: String,
required: true
},
data: {
type: Array,
required: true,
default: () => []
}
},
data() {
return {
chart: null
};
},
computed: {
...mapState(['login']),
},
watch: {
data: {
handler(newData) {
if (this.chart) {
this.updateChart(newData);
}
},
deep: true
}
},
mounted() {
this.initChart();
},
beforeDestroy() {
if (this.chart) {
this.chart.dispose();
}
},
methods: {
getMockData() {
return [
{ value: Math.floor(Math.random() * 100), name: '浅睡', percentage: '40%', itemStyle: { color: '#2ed7ee' } },
{ value: Math.floor(Math.random() * 100), name: '深睡', percentage: '30%', itemStyle: { color: '#5b8ff9' } },
{ value: Math.floor(Math.random() * 100), name: '清醒', percentage: '30%', itemStyle: { color: '#f56c6c' } }
];
},
initChart() {
this.chart = echarts.init(this.$refs.main1);
const dataToUse = this.data.length ? this.data : this.getMockData();
this.chart.setOption(this.getChartOptions(dataToUse));
},
updateChart(newData) {
const dataToUse = newData.length ? newData : this.getMockData();
this.chart.setOption(this.getChartOptions(dataToUse));
},
getChartOptions(data) {
return {
title: {
text: '睡眠',
subtext: '阶段',
left: 'center',
top: '40%',
left: '29%',
textAlign: 'center',
textStyle: { fontSize: 17, color: '#ffffff' },
subtextStyle: { fontSize: 17, color: '#ffffff' }
},
tooltip: {
trigger: 'item',
formatter: ({ marker, name, value }) => `${marker} ${name}: ${value}分钟`
},
label: {
show: true,
color: '#fff',
position: 'outside',
formatter: ({ data }) => `${data.percentage}`
},
emphasis: {
label: {
show: true,
fontSize: 20,
fontWeight: 'bold',
color: '#fff'
}
},
labelLine: {
show: true,
lineStyle: { color: '#fff' }
},
series: [
{
name: '',
type: 'pie',
radius: ['40%', '70%'],
center: ['30%', '50%'],
data
}
]
};
}
}
};
</script>
<style scoped>
#main1 {
width: 560px;
height: 180px;
}
</style>
自定义tooltip:{}
tooltip:{ trigger:"item", formatter:({marker,name,value,percentage})=>{ `${marker}${name}${value}` } }
marker就是小圆点