小程序使用echarts封装成自定义组件的实现方法

2021/6/7 20:58:30

本文主要是介绍小程序使用echarts封装成自定义组件的实现方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

小程序中自定义 echarts 组件,实现复用的方法。

1下载echarts

官网下载

2 json 中引入echarts 组件

"usingComponents": {
        "ec-canvas": "../ec-canvas/ec-canvas"
    }

3 js 中引入echarts 组件及方法

import * as echarts from '../ec-canvas/echarts'
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        chartLineId: { type: String },
        canvasId: { type: String },
        height: { type: String },
        options: { type: Object }
    },

    /**
     * 组件的初始数据
     */
    data: {
        ec: {
            lazyLoad: true, // 延迟加载
        },
    },
    lifetimes: {
        ready() {
            this[this.data.chartLineId] = this.selectComponent('#' + this.data.chartLineId);

            this.getData();
        },
        detached(e) {
            this[this.data.chartLineId] = null
            this[this.data.canvasId] = null
        },
    },

    /**
     * 组件的方法列表
     */
    methods: {
        getData() {
            this.initChart();
        },
        initChart() {
            this[this.data.chartLineId].init((canvas, width, height, dpr) => {
                const chart = echarts.init(canvas, null, {
                    width: width,
                    height: height,
                    devicePixelRatio: dpr // new
                })

                chart.setOption(this.getOption())
                return chart
            })
        },
        getOption() {
            var option = this.data.options;
            return option;
        },
    }
})

4 wxml

子组件

<view style="height: {{ height }};width:100%">
      <ec-canvas id="{{ chartLineId }}" canvas-id="{{ canvasId }}" ec="{{ec}}" options="{{options}}"></ec-canvas>
</view>

父组件

 <chart options="{{ options }}" canvasId="{{aa}}" chartLineId="{{bb}}" height="300px"></chart>


这篇关于小程序使用echarts封装成自定义组件的实现方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程