原因
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>非 APP、H5 环境不支持</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'
}
}