小程序中自定义 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>