鍍金池/ 問答/HTML/ echarts 不能獲取到高度和寬度

echarts 不能獲取到高度和寬度

在vue中使用echart出現(xiàn)問題。
我先寫一了一個(gè)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文件中調(diào)用這個(gè)組件:

<v-echart
  :width="'100%'"
  :height="'260px'"
  :option="options"
></v-echart>

運(yùn)行代碼后出現(xiàn)了警告(不是報(bào)錯(cuò)):Can't get dom width or height。圖的寬度設(shè)置100%,頁(yè)面上圖顯示的寬度是100px,但是如果設(shè)置的寬度是固定寬度,圖像寬度顯示正常,但兩種情況下警告都在,求大神告知這是為什么?
補(bǔ)充:content.vue引入了huic.vue,huic.vue引入了echart.vue,父組件通過props向子組件傳參。

這個(gè)是切換后顯示的,我在echart文檔上看到關(guān)于resize的這樣一句話:有時(shí)候圖表會(huì)放在多個(gè)標(biāo)簽頁(yè)里,那些初始隱藏的標(biāo)簽在初始化圖表的時(shí)候因?yàn)楂@取不到容器的實(shí)際高寬,可能會(huì)繪制失敗,因此在切換到該標(biāo)簽頁(yè)時(shí)需要手動(dòng)調(diào)用 resize 方法獲取正確的高寬并且刷新畫布,或者在 opts 中顯示指定圖表高寬。 所以我懷疑是因?yàn)橐婚_始的時(shí)候huice.vue,這個(gè)組件是display:none(我使用了v-show),所以我試圖在watch中加入this.chart.resize({width: this.width, height: this.height}),但是依然報(bào)同樣的警告,寬度100%依然無(wú)法體現(xiàn)。resize這個(gè)函數(shù)應(yīng)該是頁(yè)面寬高發(fā)生變化時(shí)的回調(diào)函數(shù),我tab切換后只是改變了display, resize會(huì)觸發(fā)?

回答
編輯回答
悶油瓶

watch在created之后就開始監(jiān)聽變化了,在mounted之前,props的option應(yīng)該發(fā)生了一次變化,而這時(shí)你的chartDom還沒渲染好,所以會(huì)出現(xiàn)圖中的報(bào)錯(cuò)。把chart.init操作移至mounted中就行了。還有,不用每次option變動(dòng)都去執(zhí)行init,只要執(zhí)行一下setOption就能重繪了。

另外,你DOM容器變化后才需要resize,比如調(diào)整窗口大小后,DOM寬度變小了,那就執(zhí)行以下resize(這種情況最好配合debounce使用)

還是直接上代碼吧……

watch: {
    option: function (val) {
        if (val) this.renderChart();
    }
},
mounted(){
    this.chart = echarts.init(this.$refs.myEchart);
    window.addEventListener("resize", this.onResize, false);
},
destroyed(){
    window.removeEventListener("resize", this.onResize, false);
},
methods: {
    onResize(){
        if(this.chart){
            this.chart.resize();
        }
    }
    renderChart () {
        // this.chart = echarts.init(this.$refs.myEchart);
        this.chart.setOption(this.option);
    }
}
2017年3月13日 00:02
編輯回答
鐧簞噯

你這個(gè)是切換后顯示的吧,這樣寫有點(diǎn)問題,你watch的時(shí)候調(diào)用 this.chart.resize()就行了,不用每次都初始化,把初始化放在mounted里面。

2018年8月1日 10:23