父组件请求接口后返回数据,传给子组件进行饼图渲染,因为接口是异步的,所以会导致先初始化了图表但是没数据
//父组件<template>
<div class="main-container">
<pie :pieData="state.pieData" ></pie>
</div>
</template>
<script lang="ts" setup>
import { reactive, onMounted } from "vue"
import pie from "./pie.vue"
const state: any = reactive({
pieData: [],
})
//父组件请求接口后传值给子组件,注意数据格式value:'', name:'',
async function getPieListFn() {
const res: any = await API() //使用自己的接口
state.pieData = res.data.map((item: any) => {
return {
name: item.defectName,
value: item.count
}
})
}
onMounted(() => {
getPieListFn();
});
</script>
子组件
//子组件
<template>
<div class="chart-container">
<div style="width: 100%; height: 260px" ref="chartRef" class="chart"></div>
</div>
</template>
<script lang="ts" setup>
import { ref, onMounted, watch, nextTick, onBeforeMount } from "vue"
import {Ref} from 'vue'
import * as echarts from "echarts"
const props = defineProps({
pieData: {
type: Array,
default: () => []
}
})
const data = ref<any[]>([])
let charts: any // 1. 最外层定义 echarts dom
const chartRef = ref(null)
function drawLine() {
const dom = chartRef.value
if (dom) {
// 2. 判断 dom 是否为空或未定义
if (charts != null && charts != "" && charts != undefined) {
// 3. 已存在则调用 dispose() 方法销毁
charts.dispose();
}
}
charts = echarts.init(chartRef.value)
charts.setOption({
color: ["#5087EC", "#68BBC4", "#58A55C", "#F2BD42", "#EE752F"],
tooltip: {
trigger: "item",
},
legend: {
orient: "horizontal",
left: "center",
show:false
},
series: [
{
name: "",
type: "pie",
radius: "50%",
data: data.value,
label: {
show: true
},
labelLine: {
show: true
},
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: "rgba(0, 0, 0, 0.5)"
}
}
}
]
})
}
watch(
() => props.pieData,
(newValue: any) => {
data.value = newValue
if (chartRef.value) {
nextTick(() => {
drawLine()
})
}
},
{
deep: true,
immediate: true
}
)
//调用
onMounted(() => {
//或许这里不用调用nextTick
nextTick(() => {
drawLine()
})
})
defineExpose({
drawLine
})
</script>