【BUG】已解决:Vue Echarts容器宽度设置为100%,却只展示100px

8 篇文章 0 订阅
项目描述:

请求接口有数据时,展示echarts图表(display:block),
否则就展示默认提示无数据(图表:display:none),
DOM元素设置高度400px,宽度100%;

在这里插入图片描述

// 其中父元素为 '#fatherGraph',当前元素为'#chartGraph',根据变量'elementShow'判断是否展示
<div id="fatherGraph" :class="elementShow ? 'displayBlock' : 'displayNone'">
  <div ref="chartGraph" id="chartGraph"></div>
</div>
<style>
.displayBlock{ display: block;}
.displayNone{ display: none;}
</style>
问题描述:数据从有-无-有来回切换后,echart绘图后宽度却只有100px(echart自带的)

网上查阅资料:
1、mychart.resize(); // 本项目中不生效
2、v-if ; // 本项目不可使用v-if / v-else,否则会导致报错

解决方案:

获取父元素的宽度通过element.style.width 设置元素的宽度;

公共方法提出来 放到src/utils/下的一个setAttr.js文件中,先引用后调用;

1、setAtt.js文件中声明两个方法

/** 获取元素的 css样式 */
function getStyle(obj, attr) {
  //原生js写法,兼容IE(currentStyle),第一个参数,element,第二个属性,css样式
  return obj.currentStyle
    ? obj.currentStyle[attr]
    : document.defaultView.getComputedStyle(obj, null)[attr];
}
/** 根据 父元素和当前元素 设置当前元素等CSS样式*/
function setChartAttrByFatherAndCurrentElement(fatherElement, currentElement) {
  //获取父元素
  let father = document.querySelector(fatherElement);
  if (father) {
    //获取父元素宽高
    let chartWidth = getStyle(father, "width");
    let chartHeight = getStyle(father, "height");
    //获取图表元素
    let myChart = document.querySelector(currentElement);
    //将父元素宽高赋值给图表
    myChart.style.width = chartWidth;
    myChart.style.height = chartHeight;
  }
}

export { setChartAttrByFatherAndCurrentElement };

2、在.vue文件中引入setAttr.js文件:

import {setChartAttrByFatherAndCurrentElement} from "@/utils/setAttr";

3、在返回数据时,绘图前调用

/** 传入父元素,和当前元素: 解决echart图宽度为100px问题*/
setChartAttrByFatherAndCurrentElement("#fatherGraph", "#chartGraph"); // 父元素 fatherGraph,当前元素chartGraph

正确展示:
在这里插入图片描述

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值