uniapp微信小程序使用echarts踩坑

1.下载自定义echarts

小程序对包的大小有要求,所以这边采用自定义下载echarts.js下载链接
将下载的js,存放进入项目(没有位置要求)

2.下载mpvue-echarts

npm i mpvue-echarts 安装之后找到mpvue-echarts文件拷贝出来只保留src文件
保留src
打开echarts.vue文件进行如下修改(可以直接拷贝使用,记得修改echarts.js的路径)

<template>
	<canvas v-if="canvasId" class="ec-canvas" :id="canvasId" :canvasId="canvasId" @touchstart="touchStart"
		@touchmove="touchMove" @touchend="touchEnd" @error="error">
	</canvas>
</template>

<script>
	import * as echarts from '../../echarts/echarts.min.js';
	import WxCanvas from './wx-canvas';

	function wrapTouch(e) {
		for (let i = 0; i < e.mp.touches.length; i += 1) {
			const touch = e.mp.touches[i];
			touch.offsetX = touch.x;
			touch.offsetY = touch.y;
		}
		return e;
	}

	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,
			},
		},
		onReady() {
			// if (!this.echarts) {
			// 	console.warn('组件需绑定 echarts 变量,例:<ec-canvas id="mychart-dom-bar" ' +
			// 		'canvas-id="mychart-bar" :echarts="echarts"></ec-canvas>');
			// 	return;
			// }

			if (!this.lazyLoad) this.init();
		},
		methods: {
			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);

				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();
			},
			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];
				this.handler.dispatch('mousedown', {
					zrX: touch.x,
					zrY: touch.y,
				});
				this.handler.dispatch('mousemove', {
					zrX: touch.x,
					zrY: touch.y,
				});
				this.processGesture(wrapTouch(e), 'start');
			},
			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];
				this.handler.dispatch('mousemove', {
					zrX: touch.x,
					zrY: touch.y,
				});
				this.processGesture(wrapTouch(e), 'change');
			},
			touchEnd(e) {
				const {
					disableTouch,
					chart
				} = this;
				if (disableTouch || !chart) return;
				const touch = e.mp.changedTouches ? e.mp.changedTouches[0] : {};
				this.handler.dispatch('mouseup', {
					zrX: touch.x,
					zrY: touch.y,
				});
				this.handler.dispatch('click', {
					zrX: touch.x,
					zrY: touch.y,
				});
				this.processGesture(wrapTouch(e), 'end');
			},
		},
	};
</script>

<style scoped>
	.ec-canvas {
		width: 100%;
		height: 100%;
	}
</style>

3.使用(可直接拷贝使用,注意echarts的位置)

<template>
  <div class="container">
    <div class="wrap">
      <mpvue-echarts :onInit="onInit" />
    </div>
  </div>
</template>

<script>
import * as echarts from '../../components/echarts/echarts.min.js'
import mpvueEcharts from '../../components/mpvue-echarts/src/echarts.vue'

let chart = null

function initChart (canvas, width, height) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height
  })
  canvas.setChart(chart)

  var option = {
    color: ['#37a2da', '#32c5e9', '#67e0e3'],
    tooltip: {
      trigger: 'axis',
      axisPointer: { // 坐标轴指示器,坐标轴触发有效
        type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'
      },
      confine: true
    },
    legend: {
      data: ['热度', '正面', '负面']
    },
    grid: {
      left: 20,
      right: 20,
      bottom: 15,
      top: 40,
      containLabel: true
    },
    xAxis: [
      {
        type: 'value',
        axisLine: {
          lineStyle: {
            color: '#999'
          }
        },
        axisLabel: {
          color: '#666'
        }
      }
    ],
    yAxis: [
      {
        type: 'category',
        axisTick: { show: false },
        data: ['汽车之家', '今日头条', '百度贴吧', '一点资讯', '微信', '微博', '知乎'],
        axisLine: {
          lineStyle: {
            color: '#999'
          }
        },
        axisLabel: {
          color: '#666'
        }
      }
    ],
    series: [
      {
        name: '热度',
        type: 'bar',
        label: {
          normal: {
            show: true,
            position: 'inside'
          }
        },
        data: [300, 270, 340, 344, 300, 320, 310],
        itemStyle: {
          emphasis: {
            color: '#37a2da'
          }
        }
      },
      {
        name: '正面',
        type: 'bar',
        stack: '总量',
        label: {
          normal: {
            show: true
          }
        },
        data: [120, 102, 141, 174, 190, 250, 220],
        itemStyle: {
          emphasis: {
            color: '#32c5e9'
          }
        }
      },
      {
        name: '负面',
        type: 'bar',
        stack: '总量',
        label: {
          normal: {
            show: true,
            position: 'left'
          }
        },
        data: [-20, -32, -21, -34, -90, -130, -110],
        itemStyle: {
          emphasis: {
            color: '#67e0e3'
          }
        }
      }
    ]
  }

  chart.setOption(option)
  return chart
}

export default {
  data () {
    return {
      echarts,
      onInit: initChart
    }
  },

  components: {
    mpvueEcharts
  },

  onShareAppMessage () {}
}
</script>

<style scoped>
.wrap {
  width: 500px;
  height: 300px;
}
</style>

4.可能出现的问题

1.t.addEventListener 报错
解决: 打开下载的echarts.js,全局搜索e(t.echarts = {}),后面的function(t)修改成function(t, window, document)
随后在后面添加代码

var isDomLevel2 = (typeof window !== "undefined") && !!window.addEventListener

在这里插入图片描述

然后全局搜索Le(t, e, n, i)和Pe(t, e, n, i)修改如下

function Le(t, e, n, i) {
		if (isDomLevel2) {
			t.addEventListener(e, n, i)
		} else {
			t.attachEvent("on", e, n)
		}

	}

	function Pe(t, e, n, i) {
		if (isDomLevel2) {
			t.removeEventListener(e, n, i)
		} else {
			t.detachEvent('on',e,n)
		}
		
	}

以上是个人遇见的问题,希望对大家有所帮助.

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值