uniapp使用echarts,App端formatter无法显示问题

原因

uniapp运行在app端的时候,formatter返回的函数uniapp无法解析

解决方案

自定义一个属性替代formatter,但属性值必须是字符串,以便uniapp可以正常取到值,然后我们将字符串使用 eval() 转换为函数

代码部分

以下代码可以直接使用,但注意所需依赖的引入

<template>
	<view class="chart-area">
		<!-- #ifdef APP-PLUS || H5 -->
		<view @click="echarts.onClick" :prop="option" :change:prop="echarts.updateEcharts" class="echarts" id="echarts">
		</view>
		<!-- <button @click="changeOption">更新数据</button> -->
		<!-- #endif -->
		<!-- #ifndef APP-PLUS || H5 -->
		<view>APPH5 环境不支持</view>
		<!-- #endif -->
	</view>
</template>
<script>
	export default {
		props: {
			option: {
				type: Object,
				default: () => {
					return {}
				},
				required: true
			}
		},
		methods: {
			onViewClick(options) {
				console.log(options)
			}
		}
	}
</script>

<script module="echarts" lang="renderjs">
	let myChart = {
		setOption: () => {}
	}
	export default {
		mounted() {
			if (typeof window.echarts === 'function') {
				this.initEcharts()
			} else {
				const script = document.createElement('script')
				script.src = 'static/echarts.min.js'
				script.onload = this.initEcharts.bind(this)
				document.head.appendChild(script)
			}
		},
		methods: {
			initEcharts() {
				myChart = echarts.init(this.$el)
				myChart.setOption(this.option)
			},
			updateEcharts(newValue, oldValue, ownerInstance, instance) {
				// 关键代码
				if (newValue) {
					// 如果有多个不同属性使用到了formatter,可以根据需求添加条件判断
					// 个人水平有限,没有想到一个可以完全匹配到formatter属性的方法,只好一个个条件的判断
					if (newValue.tooltip && newValue.tooltip.formatterFunction) {
						newValue.tooltip.formatter = this.toFunction(newValue.tooltip.formatterFunction)
					}
				}
				myChart.setOption(newValue)
			},
			// 转换为函数的方法
			toFunction(e) {
				return eval('(' + e + ')')
			},
			onClick(event, ownerInstance) {
				// 调用 service 层的方法
				ownerInstance.callMethod('onViewClick', {
					test: 'test'
				})
			}
		}
	}
</script>

<style scoped>
	.chart-area {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.echarts {
		width: 100%;
		height: 100%;
	}
</style>
// 配置demo
lineOption: {
	color: ['#44c685'],
	tooltip: {
		trigger: "axis",
		axisPointer: {
			type: 'cross',
		},
		formatterFunction: `(params) => {
			let str = '<span style="color: #44c685;font-size: 18px;">' + params[0].data + '</span> <span style="color: #fff;font-size: 12px;">xxx</span>'
			return str;
		}`,
		backgroundColor: '#333'
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值