iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >uniapp引用echarts的详细步骤(附柱状图实例)
  • 873
分享到

uniapp引用echarts的详细步骤(附柱状图实例)

2024-04-02 19:04:59 873人浏览 独家记忆
摘要

相信很多小伙伴对于echarts这个东西应该不会陌生,我在网上看到很多文章,那么他到底是怎么用的呢,却是五花八门,我现在就来总结一下我的方法。 如果使用npm全局安装,太麻烦,这里推

相信很多小伙伴对于echarts这个东西应该不会陌生,我在网上看到很多文章,那么他到底是怎么用的呢,却是五花八门,我现在就来总结一下我的方法。

如果使用npm全局安装,太麻烦,这里推荐使用官网(ECharts 在线构建)定制下载,这样会方便我们使用。

选择柱状图,折线图,饼图;这三样是平常较常用到的;

坐标系选择直角坐标系;

组件可以全选,也可以选择自己所需要的,在这里个人建议除了工具栏不选,其他都选上;下载后的文件为echarts.min.js,建议把他放在static内。

好了,来到下一步,我们需要在components内创建一个echarts.Vue,把这段代码复制下来,放到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: {
			
			init() {
				this.chart = echarts.init(this.$el)
				this.update(this.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)
					}
 
				}
			},
			
			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]
				}
			},
			
			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
				}
			},
			
			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
				}
			},
			
			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>

接下来就可以在所需要使用echarts的页面上,在script内引入该组件,并注册该组件,注册完后你需要复制以下代码

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柱状图使用 ,我也是走了很多弯路,看了许多的文章,觉得每个人的方法都不同,我只是把我认为好的方法放上来,希望对大家有所帮助。

最后附上一张效果图 (当然,这些颜色都是可改的,具体可以看文档或者来问一下我,我都非常乐意解答)

附:报错:this.echarts.setCanvasCreator is not a function 的解决办法

echarts.vue页面引起的  prors不能传递方法

将刚才定制的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内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: uniapp引用echarts的详细步骤(附柱状图实例)

本文链接: https://www.lsjlt.com/news/165375.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作