猿问

echarts 不能获取到高度和宽度

在vue中使用echart出现问题。
我先写一了一个echart组件在echart.vue

然后我在huic.vue文件中调用这个组件:


<v-echart

  :width="'100%'"

  :height="'260px'"

  :option="options"

></v-echart>

运行代码后出现了警告(不是报错):Can't get dom width or height。图的宽度设置100%,页面上图显示的宽度是100px,但是如果设置的宽度是固定宽度,图像宽度显示正常,但两种情况下警告都在,求大神告知这是为什么?

补充:content.vue引入了huic.vue,huic.vue引入了echart.vue,父组件通过props向子组件传参。


这个是切换后显示的,我在echart文档上看到关于resize的这样一句话:有时候图表会放在多个标签页里,那些初始隐藏的标签在初始化图表的时候因为获取不到容器的实际高宽,可能会绘制失败,因此在切换到该标签页时需要手动调用 resize 方法获取正确的高宽并且刷新画布,或者在 opts 中显示指定图表高宽。 所以我怀疑是因为一开始的时候huice.vue,这个组件是display:none(我使用了v-show),所以我试图在watch中加入this.chart.resize({width: this.width, height: this.height}),但是依然报同样的警告,宽度100%依然无法体现。resize这个函数应该是页面宽高发生变化时的回调函数,我tab切换后只是改变了display, resize会触发?


绝地无双
浏览 4570回答 1
1回答

皈依舞

watch在created之后就开始监听变化了,在mounted之前,props的option应该发生了一次变化,而这时你的chartDom还没渲染好,所以会出现图中的报错。把chart.init操作移至mounted中就行了。还有,不用每次option变动都去执行init,只要执行一下setOption就能重绘了。另外,你DOM容器变化后才需要resize,比如调整窗口大小后,DOM宽度变小了,那就执行以下resize(这种情况最好配合debounce使用)还是直接上代码吧……watch: {&nbsp; &nbsp; option: function (val) {&nbsp; &nbsp; &nbsp; &nbsp; if (val) this.renderChart();&nbsp; &nbsp; }},mounted(){&nbsp; &nbsp; this.chart = echarts.init(this.$refs.myEchart);&nbsp; &nbsp; window.addEventListener("resize", this.onResize, false);},destroyed(){&nbsp; &nbsp; window.removeEventListener("resize", this.onResize, false);},methods: {&nbsp; &nbsp; onResize(){&nbsp; &nbsp; &nbsp; &nbsp; if(this.chart){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.chart.resize();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; renderChart () {&nbsp; &nbsp; &nbsp; &nbsp; // this.chart = echarts.init(this.$refs.myEchart);&nbsp; &nbsp; &nbsp; &nbsp; this.chart.setOption(this.option);&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答