一、安装
pnpm i echarts --save
推荐大家一个echars社区,里面又各种图表示例https://www.makeapie.cn/echarts
二、 封装饼图组件(PieEcharts.vue)
注意:容器的给宽高
<template>
<div ref="pieChart" class="w-full h-full bg-fff" />
</template>
<script setup lang="ts">
import { onMounted, ref, markRaw, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'
import { sleep } from '@/utils/sleep'
const props = defineProps({
// 接受父组件传递用来渲染的数据
echartsData: {
type: Object,
default: () => {
return {}
},
},
// 接受父组件传递的图表颜色
color: {
type: Array,
default: () => {
return ['#dee2ea', '#21be6d']
},
},
})
const pieChart = ref()
let myChart = ref<any>(null)
const initEcharts = (data: any) => {
if (myChart.value) destroyEcharts()
// 标记一个对象,使其永远不会再成为响应式对象
myChart.value = markRaw(echarts.init(pieChart.value))
// todo option用来设置图标的配置项
const option = {
color: props.color,
series: [
{
type: 'pie',
radius: ['40%', '60%'],
itemStyle: {
borderRadius: 10,
borderColor: '#fff',
borderWidth: 2,
},
label: {
alignTo: 'edge',
formatter: '{name|{b}}\n{time|{c}}', //键名和键值都显示
minMargin: 5,
edgeDistance: 10,
lineHeight: 15,
rich: {
time: {
fontSize: 16,
color: '#121212', //修改键值的样式
align: 'center',
},
b: {
color: '#5f5f5f',
fontSize: 16,
fontWeight: 'bold',
lineHeight: 33,
align: 'center',
},
c: {
color: '#121212',
fontSize: 16,
fontWeight: 'bold',
},
},
},
labelLine: {
show: true,
},
data: [
{ value: data.unRegNum || '', name: '未报到'},
{ value: data.regNum || '', name: '已报到' },
],
},
],
}
echartClick()
myChart.value.setOption(option)
}
const destroyEcharts = () => {
if (myChart.value) {
myChart.value.dispose()
myChart.value = null
}
}
// 图标点击事件
const echartClick = () => {
myChart.value.on('click', (params: any) => {
wyGo(`/registration/list?type=${params.data.type}`)
})
}
onMounted(() => {
watch(
() => props.echartsData,
async (val: any) => {
await sleep(500)
initEcharts(val)
},
{ immediate: true }
)
})
onUnmounted(() => {
destroyEcharts()
})
</script>
<style lang="scss"></style>
三、封装sleep.ts
/**
* 延迟函数
* @param t 毫秒
*/
export function sleep(t: number) {
return new Promise(resolve => setTimeout(resolve, t))
}
四、模板引用组件
<pie-echarts :echarts-data="echartsData" />