如下图所示
对应代码是这样的
<template>
<div style="width: 100%; height: 100%">
<div style="width: 100%;height: 20px;display: flex; ">
<span style=" color: #24a0f0;font-size: 15px;cursor: pointer;" @click="toggleVisiable">平均激活率{{
this.allAver
}}%</span>
<span v-show="showAll" style="margin-left:1%;color: #24a0f0;font-size: 15px;">天猫平均激活率{{
this.tmAver
}}%</span>
<span v-show="showAll" style="margin-left:1%;color: #24a0f0;font-size: 15px;">拼多多平均激活率{{
this.pddAver
}}%</span>
</div>
<div ref="chart" id="orderTrends" style="width: 100%; height: 350px;"></div>
</div>
</template>
上面我设置外部盒子和echarts盒子的宽度都是100%我的父组件宽度也是100%导致出现这样的原因是 echarts在初始化的时候没有指定宽高导致的,所以我查了echarts官方文档里是这样说的
指定图表的大小
如果图表容器不存在宽度和高度,或者,你希望图表宽度和高度不等于容器大小,也可以在初始化的时候指定大小。
所以我的解决办法是这样的,利用echarts需要渲染的数据进行判断如果有值那么自然会渲染echarts这样就避免初始阶段拿不到宽度的情况
<div v-show="this.orderData" ref="chart" id="orderTrends" style="width: 100%; height: 350px;"></div>
echarts的options里多设置一行 this.chart.resize()来判断屏幕变化
this.chart.setOption(option);
this.chart.resize()
我让echarts盒子根据数据是否存在来判断是否渲染,这样相当于是数据再渲染的时候会再次设置这个宽度这样初始化就不会出现宽度只有一半或者显示不全的问题了。
我还有另外一步 避免数据没有检测到我是放到$nextTick里面进行的 包括接口的调用
mounted() {//我写在了mounted created里的话 可能数据和echarts之间有时间差的问题
this.$nextTick(() => {
this.chartDom = document.getElementById("buyuser");
this.load();//这个接口调用函数
// Dynamically load ECharts when the component is mounted
import("echarts").then((echarts) => {
this.myChart = echarts.init(this.chartDom);
this.initChart();//echarts渲染函数
});
});
},