uniapp集成ECharts步骤与柱状图实战

作者:工具松鼠

时间:2026-10-25

浏览:484

本文详解在uniapp中集成ECharts的方法,推荐通过官网定制下载echarts.min.js以简化流程。通过封装echarts.vue组件并配合renderjs技术,实现数据可视化。文中提供完整的柱状图配置代码及常见报错解决方案,帮助开发者快速上手。

文章目录

ECharts集成方案概述

ECharts作为数据可视化工具广为人知,但网上关于其具体用法的技术方案繁杂多样。本文旨在梳理并总结一种经过验证的实用集成路径,帮助开发者避开常见误区。

定制下载与文件放置

相比通过npm进行全局安装带来的复杂性,建议直接访问ECharts官网的在线构建工具进行定制下载。这种方式能按需生成文件,显著降低引入成本并提升使用便捷性。

在定制构建时,建议勾选柱状图、折线图和饼图这三种日常开发中使用频率较高的图表类型,以满足大部分基础可视化需求。

ECharts集成方案概述

坐标系配置请选择直角坐标系,这是绘制上述常规图表的标准设置。

ECharts集成方案概述

组件模块方面,建议全选或仅排除工具栏模块,其余组件保持启用状态,以确保功能完整性。下载生成的echarts.min.js文件应放置于项目的static目录下,便于统一管理和引用。

ECharts集成方案概述

组件封装与页面引入

接下来,在项目的components目录中创建名为echarts.vue的组件文件。将后续提供的组件基础代码复制并粘贴至该文件中,完成组件的结构定义。

<template>
	<view>
		<view class="echarts" :prop="option" :change:prop="echarts.update"></view>
	</view>
</template>
 
<script>
	export default {
		name: 'Echarts',
		props: {
			option: {
				type: Object,
				required: true
			}
		}
	}
</script>
 
<script module="echarts" lang="renderjs">
	export default {
		data() {
			return {
				chart: null
			}
		},
		mounted() {
			if (typeof window.echarts === 'object') {
				this.init()
			} else {
				// 动态引入类库
				const script = document.createElement('script')
				script.src = './static/echarts.min.js'
				// script.src = './static/echarts/echarts.min.js'
				script.onload = this.init
				document.head.appendChild(script)
			}
		},
		methods: {
			/**
			 * 初始化echarts
			 */
			init() {
				this.chart = echarts.init(this.$el)
				this.update(this.option)
			},
			/**
			 * 监测数据更新
			 * @param {Object} option
			 */
			update(option) {
				if (this.chart) {
					// 因App端,回调函数无法从renderjs外传递,故在此自定义设置相关回调函数
					if (option) {
						// tooltip
						if (option.tooltip) {
							// 判断是否设置tooltip的位置
							if (option.tooltip.positionStatus) {
								option.tooltip.position = this.tooltipPosition()
							}
							// 判断是否格式化tooltip
							if (option.tooltip.formatterStatus) {
								option.tooltip.formatter = this.tooltipFormatter(option.tooltip.formatterUnit, option
									.tooltip.formatFloat2, option.tooltip.formatThousands)
							}
						}
						// if (option.xAxis[0].data.length >= 5) {
						// 	option.xAxis[0].axisLabel.formatter = function formatter(params) {
						// 		if (params > 5) {
						// 			return params;
						// 		}
						// 		var maxLength = 4;
						// 		//判断长度,超出使用...代替
						// 		if (params && params.length > maxLength) {
						// 			return params.substring(0, maxLength - 1) + '...';
						// 		} else {
						// 			return params;
						// 		}
						// 	}
						// } else if(option.xAxis[0].data.length === 1){
						// 	option.xAxis[0].axisLabel.formatter = function formatter(params) {
						// 		return params
						// 	}
						// } else {
						// 	option.xAxis[0].axisLabel.formatter = function formatter(params) {
						// 		if (params > 5) {
						// 			return params;
						// 		}
						// 		var maxLength = 6;
						// 		//判断长度,超出使用...代替
						// 		if (params && params.length > maxLength) {
						// 			return params.substring(0, maxLength - 1) + '...';
						// 		} else {
						// 			return params;
						// 		}
						// 	}
						// }
						// 设置新的option
						this.chart.setOption(option, option.notMerge)
					}
 
				}
			},
			/**
			 * 设置tooltip的位置,防止超出画布
			 */
			tooltipPosition() {
				return (point, params, dom, rect, size) => {
					//其中point为当前鼠标的位置,size中有两个属性:viewSize和contentSize,分别为外层div和tooltip提示框的大小
					let x = point[0]
					let y = point[1]
					let viewWidth = size.viewSize[0]
					let viewHeight = size.viewSize[1]
					let boxWidth = size.contentSize[0]
					let boxHeight = size.contentSize[1]
					let posX = 0 //x坐标位置
					let posY = 0 //y坐标位置
					if (x < boxWidth) { //左边放不开
						posX = 5
					} else { //左边放的下
						posX = x - boxWidth
					}
					if (y < boxHeight) { //上边放不开
						posY = 5
					} else { //上边放得下
						posY = y - boxHeight
					}
					return [posX, posY]
				}
			},
			/**
			 * tooltip格式化
			 * @param {Object} unit 数值后的单位
			 * @param {Object} formatFloat2 是否保留两位小数
			 * @param {Object} formatThousands 是否添加千分位
			 */
			tooltipFormatter(unit, formatFloat2, formatThousands) {
				return params => {
					let result = ''
					unit = unit ? unit : ''
					for (let i in params) {
						if (i == 0) {
							result += params[i].axisValueLabel
						}
						let value = '--'
						if (params[i].data !== null) {
							value = params[i].data
							// 保留两位小数
							if (formatFloat2) {
								value = this.formatFloat2(value)
							}
							// 添加千分位
							if (formatThousands) {
								value = this.formatThousands(value)
							}
						}
						// #ifdef H5
						result += '\n' + params[i].seriesName + ':' + value + ' ' + unit
						// #endif
 
						// #ifdef APP-PLUS
						result += '<br/>' + params[i].marker + params[i].seriesName + ':' + value + ' ' + unit
						// #endif
					}
					return result
				}
			},
			/**
			 * 保留两位小数
			 * @param {Object} value
			 */
			formatFloat2(value) {
				let temp = Math.round(parseFloat(value) * 100) / 100
				let xsd = temp.toString().split('.')
				if (xsd.length === 1) {
					temp = (isNaN(temp) ? '0' : temp.toString()) + '.00'
					return temp
				}
				if (xsd.length > 1) {
					if (xsd[1].length < 2) {
						temp = temp.toString() + '0'
					}
					return temp
				}
			},
			/**
			 * 添加千分位
			 * @param {Object} value
			 */
			formatThousands(value) {
				if (value === undefined || value === null) {
					value = ''
				}
				if (!isNaN(value)) {
					value = value + ''
				}
				let re = /\d{1,3}(?=(\d{3})+$)/g
				let n1 = value.replace(/^(\d+)((\.\d+)?)$/, function(s, s1, s2) {
					return s1.replace(re, '$&,') + s2
				})
				return n1
			}
		}
	}
</script>
 
<style lang="scss" scoped>
	.echarts {
		width: 100%;
		height: 100%;
	}
</style>

在需要使用图表的页面中,于script部分引入上述echarts.vue组件,并完成全局或局部注册。注册完成后,需参考提供的配置代码示例,初始化图表数据与选项。

import echarts from '@/components/echarts.vue';
export default {
	// 注册组件
	components: {
         echarts
	},
     data(){
         return{
             option:{}
         }
     },
     methods:{
        logstatrt() {
		// console.log('初次调用');
		this.option = {
			notMerge: true,
			backgroundColor": "#F8FAFF",
			tooltip: {
				trigger: 'axis',
				showContent: this.showContent,
				axisPointer: {
					type: 'shadow',
					label: {
    					show: true
					},
				},
			},
			toolbox: {
				padding: [200, 0, 0, 0],
				show: true,
				feature: { //工具配置项
    				mark: {
						show: true
					},
					dataView: { //数据视图工具,可以展现当前图表所用数据
						show: true, //是否显示该工具
						readOnly: false //是否不可编辑
					},
					magicType: {
						show: true, //是否显示该工具
						type: ['line', 'bar'] //启用的动态类型
					},
					restore: {
						show: true //是否显示该工具
					},
					saveAsImage: {
						show: true //是否显示该工具
						}
					}
				},
				calculable: false, //是否显示拖拽的手柄
				// itemHeight: 0,
    			legend: { //图例组件
					data: [{
						name: '进入数',
					}, {
						name: '出去数'
					}],
					itemGap: 24,
					padding: [16, 0, 0, 0],
					// y: 'bottom',
					itemHeight: 8, //高
					itemWidth: 8, //宽
					icon: 'circle' //设置为圆
				},
				grid: {
					top: '15%',
					left: '4%',
					right: '4%',
					bottom: '6%',
					containLabel: true
				},
				xAxis: [{
					show: true,
					type: 'category', //坐标轴类型
					// boundaryGap:false, //解决数据与线不对应问题
					data: ['7.1', '7.2', '7.3', '7.4', '7.5', '7.6', '7.7', '7.8', '7.9', '7.10','7.11' ],
					// offset:50,
					//['7.1', '7.2', '7.3', '7.4', '7.5', '7.6', '7.7', '7.8', '7.9', '7.10','7.11', ], //this.xList, //obama_budget_2012.names
					axisLabel: {
						color: '#7F84B5',
						fontWeight: 300,
						interval: 0,
						},
						axisTick: {
							show: false //刻度线
						},
						axisLine: {
							show: false, //不显示坐标轴线
						},
					}, ],
				yAxis: [{
					show: true,
					boundaryGap: false, //解决数据与线不对应问题
					type: 'value',
					// name: 'Budget (million USD)',
					// data: this.yList,
					minInterval: 1,
					axisLabel: {
						interval: 0,	
					},
					splitLine: {
						show: true,
    					lineStyle: { //背景网格线
							type: 'dashed'
						}
					},
					axisTick: {
						show: false //刻度线
					},
					axisLine: {
						show: false, //不显示坐标轴线
					},
				}],
				dataZoom: [{
					show: false,
					start: 0,
					end: 100,
					handleSize: 8
				},
				{
					type: 'inside',
					start: 0,
					end: 50,
				},
				{
					show: false,
					yAxisIndex: 0,
    				filterMode: 'empty',
					width: 12,
					height: '80%',
					showDataShadow: false,
					left: '93%',
					handleSize: 8
				}
				],
				series: [{
					name: '进入数',
					type: 'bar',
					data: ['10', '20', '30', '40', '50', '60', '70', '80', '90', '100', '110','120'],
					//['10', '20', '30', '40', '50', '60', '70', '80', '90', '100', '110','120'], // this.inNum, //obama_budget_2012.budget2011List
					color: "#00B1FF"
				},
						{
							name: '出去数',
							type: 'bar',
							data: ['10', '20', '30', '40', '50', '60', '70', '80', '90', '100', '110','120'],
							//['10', '20', '30', '40', '50', '60', '70', '80', '90', '100', '110','120'], //this.outNum, //obama_budget_2012.budget2012List
							color: "#FF6C00"
						}
					]
				};
			},         
     }
  }

完成组件注册与配置后,图表集成的核心逻辑已基本就绪。

图表渲染与配置

在页面模板中调用该组件,需明确指定图表容器的id属性,并将包含配置项的option对象作为参数传入。同时,在组件标签上设置好图表的宽高样式。完成上述步骤后,页面中即可渲染出对应的柱状图。

<echarts :option="option" id="myChart" style="height: 110vw;margin-left: 2vw;width: 100%;padding: 4vw 0 0 0;"></echarts>

以上即为一个基础ECharts柱状图的完整实现流程。鉴于不同开发者遇到的环境差异较大,本文分享的是经过实践验证的有效方案,期望能为遇到类似问题的开发者提供参考。

文末附带了最终的渲染效果截图。需要注意的是,图表的颜色等视觉样式均可通过配置进行修改,具体细节可查阅官方文档或进一步交流探讨。

ECharts集成方案概述

常见报错与解决方案

此外,针对集成过程中可能出现的报错:this.echarts.setCanvasCreator is not a function,本文提供了相应的排查与解决思路。

该报错通常源于echarts.vue组件内部props属性无法正确传递方法至renderjs作用域,需检查组件通信机制。

解决此问题的关键步骤之一,是确保在组件中正确引入之前定制下载的echarts.js文件,保证依赖路径无误。

import * as echarts from '@/common/echarts.min.js';

在调用相关方法或传递参数时,务必注意加上this关键字,以确保上下文指向正确,避免引用错误。

this.ctx = wx.createCanvasContext(canvasId,this);  

const query = wx.createSelectorQuery().in(this);  

开发者也可直接复制文中提供的完整代码片段进行替换,但请务必根据实际项目结构调整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 WxCanvas from './wx-canvas';  
import * as echarts from '@/common/echarts.min.js';
 
export default {  
  props: {  
    // echarts: {  
    //   required: true,  
    //   type: Object,  
    //   default() {  
    //     return echarts;  
    //   }  
    // },  
    onInit: {  
      required: true,  
      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() {  
    this.echarts = echarts;  
 
    if (!this.echarts) {  
      console.warn('组件需绑定 echarts 变量,例:<ec-canvas id="mychart-dom-bar" ' + 'canvas-id="mychart-bar" :echarts="echarts"></ec-canvas>');  
      return;  
    }  
 
    console.log('echarts');  
    console.log(this.onInit);  
 
    if (!this.lazyLoad) this.init();  
  },  
  methods: {  
    init() {  
      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;  
      }  
 
      if (!this.onInit) {  
        console.warn('请传入 onInit 函数进行初始化');  
        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(), 200);  
            return;  
          }  
 
          this.chart = this.onInit(canvas, res.width, res.height);  
        })  
        .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];  
      chart._zr.handler.dispatch('mousedown', {  
        zrX: touch.x,  
        zrY: touch.y  
      });  
      chart._zr.handler.dispatch('mousemove', {  
        zrX: touch.x,  
        zrY: touch.y  
      });  
    },  
    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];  
      chart._zr.handler.dispatch('mousemove', {  
        zrX: touch.x,  
        zrY: touch.y  
      });  
    },  
    touchEnd(e) {  
      const { disableTouch, chart } = this;  
      if (disableTouch || !chart) return;  
      const touch = e.mp.changedTouches ? e.mp.changedTouches[0] : {};  
      chart._zr.handler.dispatch('mouseup', {  
        zrX: touch.x,  
        zrY: touch.y  
      });  
      chart._zr.handler.dispatch('click', {  
        zrX: touch.x,  
        zrY: touch.y  
      });  
    }  
  }  
};  
</script>  
 
<style scoped>  
.ec-canvas {  
  width: 100%;  
  height: 100%;  
  flex: 1;  
}  
</style>  

通过对上述步骤的梳理与代码示例的展示,本文总结了uniapp中ECharts集成的关键要点。

至此,关于uniapp引用ECharts的详细步骤及柱状图实例介绍完毕。如需了解更多相关内容,建议查阅本站过往文章或关注后续更新,感谢支持。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章