uniapp使用echarts _ 速度上手

uniapp使用echarts _ 速度上手

插件地址:https://ext.dcloud.net.cn/plugin?id=6983

gitee地址:https://gitee.com/suixinxingyanghao/uniapp-echarts

uniapp使用echarts的時候,需要獲取dom

是不是有很多小夥伴在app端運行的時候會發現這個會報錯

document.getElementById('id')

想了解清楚請查看:renderjs

下面用到echarts的option數據:(隨便打開一個複製option數據)

 

開始操作 - 直接上代碼

1.從 npm 獲取echarts

npm install echarts --save

2.新建組件echarts.vue

<template>
	<view>
		<view class="echarts" :id="option.id" :prop="option" :change:prop="echarts.update" @click="echarts.onClick"></view>
	</view>
</template>

<script>
	export default {
		name: 'Echarts',
		props: {
			option: {
				type: Object,
				required: true
			}
		},
		created() {
			// 設置隨機數id
			let t = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
			let id = ''
			for (let i = 0; i < 32; i++) {
				id += t.charAt(Math.floor(Math.random() * t.length))
			}
			this.option.id = id
		},
		methods: {
			/**
			 * renderjs內的點擊事件,回調到父組件
			 * @param {Object} params
			 */
			onViewClick(params) {
				this.$emit('click', params)
			}
		}
	}
</script>

<script module="echarts" lang="renderjs">
	import * as echarts from 'echarts';
	export default {
		data() {
			return {
				chart: null,
				clickData: null // echarts點擊事件的值
			}
		},
		mounted() {
			if (typeof window.echarts === 'object') {
				this.init()
			} else {
				// 動態引入類庫
				const script = document.createElement('script')
				script.src = 'echarts/echarts.min.js'
				script.onload = this.init()
				document.head.appendChild(script)
			}
		},
		methods: {
			/**
			 * 初始化echarts
			 */
			init() {
				// 根據id初始化圖表
				this.chart = echarts.init(document.getElementById(this.option.id))
				this.update(this.option)
				// echarts的點擊事件
				this.chart.on('click', params => {
					// 把點擊事件的數據緩存下來
					this.clickData = params
				})
			},
			/**
			 * 點擊事件,可傳遞到外部
			 * @param {Object} event
			 * @param {Object} instance
			 */
			onClick(event, instance) {
				console.log("onClick")
				if (this.clickData) {
					// 把echarts點擊事件相關的值傳遞到renderjs外
					instance.callMethod('onViewClick', {
						value: this.clickData.data,
						name: this.clickData.name,
						seriesName: this.clickData.seriesName
					})
					// 上次點擊數據置空
					this.clickData = null
				}
			},
			/**
			 * 監測數據更新
			 * @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.series) {
							for (let i in option.series) {
								let linearGradient = option.series[i].linearGradient
								if (linearGradient) {
									option.series[i].color = new echarts.graphic.LinearGradient(linearGradient[0],linearGradient[1],linearGradient[2],linearGradient[3],linearGradient[4])
								}
							}
						}
					}
					// 設置新的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 = x - boxWidth - 1
					}
					if (y >= boxHeight) { // 上邊放的下
						posY = y - boxHeight - 1
					}
					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>

3.頁面使用

 

提示:記得修改引入組件地址


組件地址

<template>
	<view style="display: flex;flex-direction: row;">
		<view style="width:100%;display: flex;flex-direction: column;margin-left:5%;">
			<echarts @click="hao" :option="option" style="height:600px;"></echarts>
		</view>
		<view></view>
	</view>
</template>

<script>
	import Echarts from '../../components/echarts/echarts.vue'
	export default {
		data() {
			return {
				option: {}
			};
		},
		// tabBar頁面
		onShow() {
			this.getoption();
		},
		onLoad() {
         // this.getoption();
		},
		methods: {
			hao(params) {
				console.log("123213",params)
			},
			getoption() {
				let newOption = {
					tooltip: {
						trigger: 'item'
					},
					legend: {
						top: '5%',
						left: 'center'
					},
					series: [{
						name: 'Access From',
						type: 'pie',
						radius: ['40%', '70%'],
						avoidLabelOverlap: false,
						label: {
							show: false,
							position: 'center'
						},
						emphasis: {
							label: {
								show: true,
								fontSize: '40',
								fontWeight: 'bold'
							}
						},
						labelLine: {
							show: false
						},
						data: [{
								value: 1048,
								name: 'Search Engine'
							},
							{
								value: 735,
								name: 'Direct'
							},
							{
								value: 580,
								name: 'Email'
							},
							{
								value: 484,
								name: 'Union Ads'
							},
							{
								value: 300,
								name: 'Video Ads'
							}
						]
					}]
				};
				
				this.option = newOption;
			}
		}
	};
</script>

<style></style>

收工!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章