uniapp微信小程序中使用echarts

**1、下载所需要的库
终端输入 npm install echarts mpvue-echarts --save
将node_modules中的mpvue-echarts文件夹放入components目录下,只保留其中的src文件夹

image.png
2、然后在https://echarts.apache.org/zh/builder.html定制echarts的js文件,然后下载,放到common目录下
image.png
3、以折线图为例

运行时提示this.echarts.setCanvasCreator is not a function的错误
解决方法:
1、找到components–》mpvue-echarts–》src–》echarts.vue
导入import * as echarts from ‘@/common/echarts.min’; /echarts.min.js为在线定制/
2、注释props中的echarts,如下

export default {
props: {
// echarts: {
// required: true,
// type: Object,
// default() {
// return null;
// },
// },
onInit: {
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,
},
},
3、在 onReady方法中添加 this.echarts = echarts

onReady() {
this.echarts = echarts //新增
if (!this.echarts) {
console.warn('组件需绑定 echarts 变量,例: + ‘canvas-id=“mychart-bar” :echarts=“echarts”>’);
return;
}

if (!this.lazyLoad) this.init();

},
4、init方法中修改以下3处
const canvasId = this.canvasId; //------修改------
this.ctx = wx.createCanvasContext(canvasId,this);//------修改------
const query = wx.createSelectorQuery().in(this); //------修改------

init(callback) {
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;
}

  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(), 50);
      return;
    }

    const { width, height } = res;

    if (typeof callback === 'function') {
      this.chart = callback(canvas, width, height);
    } else if (typeof this.onInit === 'function') {
      this.chart = this.onInit(canvas, width, height);
    }

    if (!this.chart) {
      return;
    }

    const { handler } = this.chart.getZr();

    this.handler = handler;
    this.processGesture = handler.proxy.processGesture || (() => {});
  }).exec();
},

参考文章:
uniapp在微信小程序中使用 ECharts
https://blog.csdn.net/wxh958548129/article/details/107520566
uni-app使用mpvue-echarts报 的解决办法
https://ask.dcloud.net.cn/article/36652

作者:jing_bao
链接:https://www.jianshu.com/p/89668afd8fa4
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。**

你可能感兴趣的:(项目点,echarts,uni-app,微信小程序)