vue中使用百度echart圖表大小問題
阿新 • • 發佈:2019-01-02
在專案中需要通過百度echarts的儀表盤來展示測試的成功率,自己封裝了個gauge的vue元件,展示出來的時候發現大小不對,整個影象被限制在了一個很矮的區間內,如下圖所示:
元件檔案如下:
<template> <!--單獨生成id,避免例項化時使用同一個div--> <div style="height:100%;width:100%;" :id="gaugeId"></div> </template> <script> import echarts from 'echarts'; import util from '@/libs/util'; export default { name: 'successRateGauge', props: ['title', 'rate'], data(){ return { gaugeInstance: null, gaugeId:util.uuid(), gaugeTitle: this.title, // 避免直接使用prop屬性導致改變父元件內容 gaugeRate: this.rate, option: { backgroundColor: '#1b1b1b', tooltip: { formatter: "{a} <br/>{c} {b}" }, series: [ { name: 'xxx', type: 'gauge', radius: "90%", //儀表大小 axisLine : { show : true, lineStyle : { // 屬性lineStyle控制線條樣式 color : [ //錶盤顏色 [ 0.5, "#DA462C" ],//0-50%處的顏色 [ 0.7, "#FF9618" ],//51%-70%處的顏色 [ 0.9, "#FFED44" ],//70%-90%處的顏色 [ 1,"#20AE51" ]//90%-100%處的顏色 ] } }, detail: {formatter:'{value}%'}, data: [{value: 0, name: '%'}] } ] } } }, methods: { getChartInstance(){ // 獲取圖表例項 this.gaugeInstance = echarts.init(document.getElementById(this.gaugeId)); }, drawGauge(){ // 畫圖 this.option.series[0].data[0].value = this.gaugeRate; this.option.series[0].name = this.gaugeTitle; this.gaugeInstance.setOption(this.option); let _this = this; window.addEventListener('resize', function () { _this.gaugeInstance.resize(); }); } }, mounted(){ this.getChartInstance(); this.drawGauge(); }, watch: { rate(){ // 這裡沒有直接監控gaugeRate,因為rate只在初始化的時候賦值給了gaugeRate, // 之後rate的改變無法更新到gaugeRate。所以只能直接監聽rate。 this.gaugeRate = this.rate; this.drawGauge(); } } }; </script>
元件沒有什麼特殊的,就是把官網的例子改造成了vue元件,方便複用。之前以為是radiu引數設定不對,於是調大了radius,從90%調到了200%,效果就是儀表盤變大了,但是還是被限制在很矮的區間裡。後來網上搜了得知,容器大小不能設定百分比,要設定具體的數值,於是將容器大小做了修改:
<template>
<!--單獨生成id,避免例項化時使用同一個div-->
<div style="height:246px;width:347px;" :id="gaugeId"></div>
</template>
之後就好了,顯示正常了。