在vue中使用echart
出现问题。
我先写一了一个echart
组件在echart.vue
:
<template>
<div :class="className"
:id="id"
:style="{height:height, width:width}"
ref="myEchart">
</div>
</template>
<script>
import echarts from 'echarts';
export default {
props: {
className: {
type: String,
default: ''
},
id: {
type: String,
default: ''
},
width: {
type: String,
default: '100%'
},
height: {
type: String,
default: '250px'
},
option: {
type: Object,
default: null
}
},
data () {
return {
chart: null
};
},
beforeDestroy () {
if (!this.chart) return;
this.chart.dispose();
this.chart = null;
},
watch: {
option: function (val, oldVal) {
if (val) this.initChart();
}
},
methods: {
initChart () {
this.chart = echarts.init(this.$refs.myEchart);
this.chart.setOption(this.option);
}
}
};
</script>
然后我在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
会触发?
watch在created之后就开始监听变化了,在mounted之前,props的option应该发生了一次变化,而这时你的chartDom还没渲染好,所以会出现图中的报错。把chart.init操作移至mounted中就行了。还有,不用每次option变动都去执行init,只要执行一下setOption就能重绘了。
另外,你DOM容器变化后才需要resize,比如调整窗口大小后,DOM宽度变小了,那就执行以下resize(这种情况最好配合debounce使用)
还是直接上代码吧……