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_modulesmpvue-echartssrcecharts.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_modulesmpvue-echartssrcecharts.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方法,写一个就可以了。
 
嗯,就酱吧。
最后放个生成出来的图。
 




原文地址:https://www.cnblogs.com/tuituji27/p/13280243.html