mpvue開發小程序,使用echarts踩坑記錄


好久沒寫博客了,主要是沒遇到什么大坑,再加上工作變動。不過最近接觸小程序開發,用的mpvue,和vue差不多,上手較容易。

在開發過程中,遇到畫圖表的需求。

期間找了很多文章參考,最后才用的組件是:mpvue-echarts,其實就是用vue把小程序的畫布組件包了一下。

比較有用的文章鏈接:

git源碼及說明:https://github.com/F-loat/mpvue-echarts

由於是一個頁面顯示多個圖表,所以還看了這個:https://github.com/F-loat/mpvue-echarts/blob/master/examples/src/pages/demos/multiCharts.vue

以上例子沒什么可說的,都寫得很清楚,例子也是可行的。

 

但是,哪有那么容易!!!

第一坑:

例子中   

<mpvue-echarts :echarts="echarts" :onInit="onInit" canvasId="demo-canvas" />
canvasId是必寫的,而且必須唯一,不唯一的話只能顯示一個,其他的隱藏。
我偏偏需要動態v-for循環出來多個圖表,循環出來的
canvasId都是一樣的,就顯示出來第一個。

我只好用:canvasId綁定,動態給賦值,但是組件就開始循環,好怕怕電腦壞掉,趕快停掉!!

ε=(´ο`*)))唉

最后,我還是動態循環出了圖表,划重點。

我把這個組件內部改了。

在node_modules\mpvue-echarts\src\echarts.vue中,
props增加參數:
    index:{
      type:String
    }
 
原來的組件是這樣的:
<canvas
    v-if="canvasId"
    class="ec-canvas"
    :id="canvasId"
    :canvasId="canvasId"
    @touchstart="touchStart"
    @touchmove="touchMove"
    @touchend="touchEnd"
    @error="error">
 </canvas>

改成這樣:

<canvas
    v-if="canvasId"
    class="ec-canvas"
    :id="canvasId + index"  //加上index
    :canvasId="canvasId + index"  //加上index
    @touchstart="touchStart"
    @touchmove="touchMove"
    @touchend="touchEnd"
    @error="error">
  </canvas>

改完組件后這樣使用,就可以在v-for中顯示多個圖表了。

<mpvue-echarts :echarts="echarts" :onInit="onInit" canvasId="demo-canvas" :index = "myCourse.nd"/> 

第二坑:
既然是動態生成,option也不可能一樣啊,所以例子中setOption的參數也需要增加,
參數從function
onInit(canvas, width, height)中傳過來,但是參數是固定的,不能隨便增加。
於是,我又改了他原來組件~~
還是在node_modules\mpvue-echarts\src\echarts.vue中,
props增加參數:
 num1:{
      type: String
    },
    num2:{
      type: String
    },
然后,他原來的init()方法是這樣的:
if (typeof callback === 'function') {
          this.chart = callback(canvas, width, height);
        } else if (typeof this.onInit === 'function') {
          this.chart = this.onInit(canvas, width, height);
        }

我改成這樣:

if (typeof callback === 'function') {
          this.chart = callback(canvas, width, height,this.num1,this.num2); //加上自己的參數
        } else if (typeof this.onInit === 'function') {
          this.chart = this.onInit(canvas, width, height,this.num1,this.num2); //加上自己的參數
        }

然后在使用的時候:

<mpvue-echarts 
            :echarts="echarts" 
            :onInit="onInit" 
            canvasId="a1"
            :index = "myCourse.nd"
            :num1 = "myCourse.finshProCredit"  //傳入自己的參數
            :num2 = "myCourse.proCredit"       //傳入自己的參數
            />

 

就可以把自己的參數傳到他的組件中,通過組件中init方法帶回到onInit方法,所以再寫onInit的時候,要這樣寫:

onInit(canvas, width, height, num1,num2) {
...
...
let option = setOption( num1,num2);
chart.setOption(option);
...
}
這樣也不需要像例子中寫很多setOption方法,寫一個就可以了。
 
嗯,就醬吧。
最后放個生成出來的圖。
 




 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM