在父组件获取到数据后传递给子组件并没有及时的更新渲染图表。在本地开发环境是没有一点问题,但发布到测试环境上每次页面加载都不渲染,点击浏览器刷新按钮后才会去渲染图表。
个人认为造成这个问题的原因:页面加载子组件dom元素此时还没有加载完成,所以看到的就是空白,只有刷新一下才可以。
解决这个问题的方法就是: 在生命周期里面使用 nextTick()待dom加载完成之后再去渲染图表```
具体实现代码:
父组件:获取到数据后通过props 传递给子组件
```javascript
<!--入驻统计折线图-->
<hostLine ref="settled" :settledData="settledData"> </hostLine>
async getSettledData() {
const result = await getProjectSettled();
if (result.success) {
if (result.data.companyCount.length === 0 && result.data.stationCount.length === 0) {
Object.assign(data.settledData);
} else {
Object.assign(data.settledData, result.data);
}
update.value = new Date().getTime();
}
},
子组件: 接收父组件传递的数据并进行 watch 监听,在生命周期onMounted里面使用 nextTick进行渲染图表就行了。
<template>
<div class="line-overview">
<div class="host-line">
<div class="host-line-title">入驻统计</div>
<div id="hostLine" style="width: 100%; height: 360px"></div>
</div>
</div>
</template>
<script lang="ts">
import * as echarts from "echarts/core";
import { TooltipComponent, LegendComponent, GridComponent, } from 'echarts/components';
import { LineChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
import { UniversalTransition } from 'echarts/features';
import { defineComponent, inject, watch, onMounted, onUnmounted, ref, shallowRef, nextTick } from "vue";
echarts.use([
TooltipComponent,
LegendComponent,
GridComponent,
LineChart,
CanvasRenderer,
UniversalTransition
]);
export default defineComponent({
props: ["settledData"],
setup(props) {
const update = inject("update");
const LineChart = shallowRef();
const drawChart = () => {
const cahrtData = props.settledData;
LineChart.value = echarts.init(document.getElementById("hostLine") as HTMLElement);
let option = {
tooltip: {
trigger: "axis",
},
legend: {
data: ['企业数量', '工位数量',]
},
grid: {
left: "3%",
right: "4%",
bottom: "3%",
containLabel: true,
},
xAxis: {
type: "category",
boundaryGap: false,
data: cahrtData?.date.reverse()
},
yAxis: {
type: "value",
scale: true,
min: (value:Record<string,number>) => {
return Math.floor(value.min / 100) * 100;
},
max: (value:Record<string,number>) => {
return Math.ceil(value.max / 100) * 100;
},
},
series: [
{
name: "企业数量",
type: "line",
stack: "Total",
data: cahrtData?.companyCount,
},
{
name: "工位数量",
type: "line",
stack: "Total",
data: cahrtData?.stationCount,
},
],
};
LineChart.value.setOption(option);
window.addEventListener("resize", () => {
LineChart.value.resize();
});
};
onMounted(() => {
watch([update], () => {
nextTick(()=>{
drawChart();
})
}, {
deep: true
})
});
onUnmounted(() => {
LineChart.value.dispose();
});
},
});
</script>
|