前期准备:
1.echarts提供了一个微信小程序原生组件,下载地址:ecomfe/echarts-for-weixin ,拿到 ec-canvas 文件夹
2. 到 echarts官网 在线定制组件包
注意:版本一定要和 ec-canvas 相同
3.将下载的 echarts.min.js 替换掉原本的 echarts.js ,小程序文件过大影响发布
4.引入
ec-canvas.json
{
"component": true,
"usingComponents": {
"ec-canvas":"../ec-canvas/ec-canvas"
}
}
ec-canvas.wxml
<view class="ec-container">
<ec-canvas id="mychart-dom-bar" canvas-id="mychart-bar" ec="{{ec}}"></ec-canvas>
</view>
注意:记得给容器设置宽高,否则会出现空白
ec-canvas.js
import * as echarts from '../../components/ec-canvas/echarts.min'
Page({
data: {
ec: {
lazyLoad: true
},
},
onReady: function () {
// 手动获取到echart节点
this.compBar = this.selectComponent('#mychart-dom-bar')
this.loadData()
},
loadData: function () {
api.getData().then(res => {
// 数据处理
const opts = {
// ...
}
if (this.chartBar) {
this.chartBar.setOption(opts)
} else {
this.initBar(opts)
}
})
},
initBar: function (option) {
if(!this.compBar){
this.compBar = this.selectComponent('#mychart-dom-bar')
}
this.compBar.init((canvas, width, height, dpr) => {
const chart = echarts.init(canvas, null, {
width: width,
height: height,
devicePixelRatio: dpr // 像素
});
chart.setOption(option)
this.chartBar = chart
return chart
})
},
});
如果需要复用,可以封装成组件
my-ec-canvas.wxml
<view class="my-ec-container">
<ec-canvas id="{{chartId}}" canvas-id="{{canvasId}}" ec="{{ec}}"></ec-canvas>
</view>
my-ec-canvas.js
import * as echarts from '../../components/ec-canvas/echarts.min'
Component({
properties: {
chartId: {
type: String,
value: null
},
canvasId: {
type: String,
value: null
},
chartOpts: {
type: Object,
value: {}
}
},
data: {
ec: {
lazyLoad: true
}
},
methods: {
initChart(options) {
if(!this.chartComp){
this.chartComp = this.selectComponent(`#${this.properties.chartId}`)
}
this.chartComp && this.chartComp.init((canvas, width, height, dpr) => {
const chart = echarts.init(canvas, null, {
width: width,
height: height,
devicePixelRatio: dpr
})
chart.setOption(options)
this.chart = chart
return chart
})
}
},
observers: {
'chartOpts': function (opts) {
if (this.chart) {
this.chart.setOption(opts)
} else {
this.initChart(opts)
}
}
}
})
使用组件,传入 id,options 配置即可文章来源:https://www.toymoban.com/news/detail-421999.html
<my-ec-canvas chartId="{{chartDomId}}" canvas-id="{{canvasId}}" chartOpts="{{optionsData}}"></my-ec-canvas>
参考文章:https://juejin.cn/post/6994742503207337991文章来源地址https://www.toymoban.com/news/detail-421999.html
到了这里,关于微信小程序使用echarts的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!