美文网首页
uni-app 小程序中使用echarts图

uni-app 小程序中使用echarts图

作者: 变量只提升声明不提升赋值 | 来源:发表于2021-05-07 15:13 被阅读0次
    1. 下载包 npm install echarts mpvue-echarts --save 下载成功后在node_modules里面会多出 echarts、mpvue-echats 、zrender 三个目录
    2. 将mpvue-echats目录下的src目录下的两个文件放进components文件夹中
    3. 由于小程序包大小限制,可以定制化echcarts( https://echarts.apache.org/zh/builder.html )并根据自身框架引入

    使用:

    <template>
    <view class="test">
                <mpvueEcharts id='test' ref='testEchart' :onInit='renders' ></mpvueEcharts>
    </view>
    </template>
    
    <script>
        import * as echarts from '@/components/echarts.min.js'  //自己下载的定制echarts文件
        import mpvueEcharts from '@/components/echarts'  //mpvue-echarts组件
    
    
    export default{
            components: {
                mpvueEcharts
            },
            data() {
                return {}
                    },
                    methods: {
                        async renders(c,w,v) {
                    let canvas = c
                    let width = w
                    let height = v
                    echarts.setCanvasCreator(() => canvas);
                    const chart = echarts.init(canvas, null, {
                        width: width,
                        height: height
                    });
                    canvas.setChart(chart);
                    let options = {
                        title: {
                            text: '基础雷达图'
                        },
                        legend: {
                            data: ['预算分配(Allocated Budget)', '实际开销(Actual Spending)', '测试(Actual Spending)']
                        },
                        radar: {
                            // shape: 'circle',
                            indicator: [{
                                    name: '销售(Sales)',
                                    max: 500
                                },
                                {
                                    name: '管理(Administration)',
                                    max: 300
                                },
                                {
                                    name: '信息技术(Information Technology)',
                                    max: 300
                                },
                                {
                                    name: '客服(Customer Support)',
                                    max: 300
                                },
                                {
                                    name: '研发(Development)',
                                    max: 300
                                },
                                {
                                    name: '市场(Marketing)',
                                    max: 300
                                }
                            ]
                        },
                        series: [{
                            name: '预算 vs 开销(Budget vs spending)',
                            type: 'radar',
                            data: [{
                                    value: [100, 200, 30, 150, 300, 180],
                                    name: '预算分配(Allocated Budget)'
                                },
                                {
                                    value: [500, 140, 100, 260, 240, 210],
                                    name: '实际开销(Actual Spending)'
                                },
                                {
                                    value: [120, 130, 100, 260, 240, 210],
                                    name: '测试(Actual Spending)'
                                }
                            ]
                        }]
                    };
                    chart.setOption(options);
                    return chart  //必须要return。。原因可以看echarts.vue是怎样调用这个函数的。
                },
                    }
    }
    </script>
    

    初始化函数需要是一个异步函数,防止dom还没渲染出来就执行了初始化函数导致报错。

    原文档上写的是还需要把echarts 对象传给组件。但是经实测。发现会报错。报this.echarts.setCanvasCreator不是函数的错误
    解决方法将echechs.main.js直接导入到echarts.vue中。

    echarts.vue完整代码如下

    <template>  
      <canvas v-if="canvasId" class="ec-canvas" :id="canvasId" :canvasId="canvasId" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd" @error="error"></canvas>  
    </template>  
    
    <script>  
    import WxCanvas from './wx-canvas';  
    import * as echarts from '@/common/js/echarts.simple.min';  
    
    export default {  
      props: {  
        // echarts: {  
        //   required: true,  
        //   type: Object,  
        //   default() {  
        //     return echarts;  
        //   }  
        // },  
        onInit: {  
          required: true,  
          type: Function,  
          default: null  
        },  
        canvasId: {  
          type: String,  
          default: 'ec-canvas'  
        },  
        lazyLoad: {  
          type: Boolean,  
          default: false  
        },  
        disableTouch: {  
          type: Boolean,  
          default: false  
        },  
        throttleTouch: {  
          type: Boolean,  
          default: false  
        }  
      },  
      onReady() {  
        this.echarts = echarts;  
    
        if (!this.echarts) {  
          console.warn('组件需绑定 echarts 变量,例:<ec-canvas id="mychart-dom-bar" ' + 'canvas-id="mychart-bar" :echarts="echarts"></ec-canvas>');  
          return;  
        }  
    
        console.log('echarts');  
        console.log(this.onInit);  
    
        if (!this.lazyLoad) this.init();  
      },  
      methods: {  
        init() {  
          const version = wx.version.version.split('.').map(n => parseInt(n, 10));  
          const isValid = version[0] > 1 || (version[0] === 1 && version[1] > 9) || (version[0] === 1 && version[1] === 9 && version[2] >= 91);  
          if (!isValid) {  
            console.error('微信基础库版本过低,需大于等于 1.9.91。' + '参见:https://github.com/ecomfe/echarts-for-weixin' + '#%E5%BE%AE%E4%BF%A1%E7%89%88%E6%9C%AC%E8%A6%81%E6%B1%82');  
            return;  
          }  
    
          if (!this.onInit) {  
            console.warn('请传入 onInit 函数进行初始化');  
            return;  
          }  
    
          const canvasId = this.canvasId;  
          this.ctx = wx.createCanvasContext(canvasId,this);  
    
          const canvas = new WxCanvas(this.ctx, canvasId);  
    
          this.echarts.setCanvasCreator(() => canvas);  
    
          const query = wx.createSelectorQuery().in(this);  
          query  
            .select(`#${canvasId}`)  
            .boundingClientRect(res => {  
              if (!res) {  
                //setTimeout(() => this.init(), 200);  
                return;  
              }  
    
              this.chart = this.onInit(canvas, res.width, res.height);  
            })  
            .exec();  
        },  
        canvasToTempFilePath(opt) {  
          const { canvasId } = this;  
          this.ctx.draw(true, () => {  
            wx.canvasToTempFilePath({  
              canvasId,  
              ...opt  
            });  
          });  
        },  
        touchStart(e) {  
          const { disableTouch, chart } = this;  
          if (disableTouch || !chart || !e.mp.touches.length) return;  
          const touch = e.mp.touches[0];  
          chart._zr.handler.dispatch('mousedown', {  
            zrX: touch.x,  
            zrY: touch.y  
          });  
          chart._zr.handler.dispatch('mousemove', {  
            zrX: touch.x,  
            zrY: touch.y  
          });  
        },  
        touchMove(e) {  
          const { disableTouch, throttleTouch, chart, lastMoveTime } = this;  
          if (disableTouch || !chart || !e.mp.touches.length) return;  
    
          if (throttleTouch) {  
            const currMoveTime = Date.now();  
            if (currMoveTime - lastMoveTime < 240) return;  
            this.lastMoveTime = currMoveTime;  
          }  
    
          const touch = e.mp.touches[0];  
          chart._zr.handler.dispatch('mousemove', {  
            zrX: touch.x,  
            zrY: touch.y  
          });  
        },  
        touchEnd(e) {  
          const { disableTouch, chart } = this;  
          if (disableTouch || !chart) return;  
          const touch = e.mp.changedTouches ? e.mp.changedTouches[0] : {};  
          chart._zr.handler.dispatch('mouseup', {  
            zrX: touch.x,  
            zrY: touch.y  
          });  
          chart._zr.handler.dispatch('click', {  
            zrX: touch.x,  
            zrY: touch.y  
          });  
        }  
      }  
    };  
    </script>  
    
    <style scoped>  
    .ec-canvas {  
      width: 100%;  
      height: 100%;  
      flex: 1;  
    }  
    </style>  
    

    相关文章

      网友评论

          本文标题:uni-app 小程序中使用echarts图

          本文链接:https://www.haomeiwen.com/subject/ikosdltx.html