在使用uniapp的echarts时,我们一般都是使用的randerjs
就是下面这些代码
<script module="echarts" lang="renderjs">
let myChart
export default {
mounted() {
if (typeof window.echarts === 'function') {
this.initEcharts()
} else {
// 动态引入较大类库避免影响页面展示
const script = document.createElement('script')
// view 层的页面运行在 www 根目录,其相对路径相对于 www 计算
script.src = 'static/echarts.js'
script.onload = this.initEcharts.bind(this)
document.head.appendChild(script)
}
},
methods: {
initEcharts() {
myChart = echarts.init(document.getElementById('saleCharts'))
// 观测更新的数据在 view 层可以直接访问到
//初始化时formatter被干掉了,因此需要加上formatter,
myChart.setOption(this.chartOption)
},
updateEcharts(newValue, oldValue, ownerInstance, instance) {
// 监听 service 层数据变更
myChart.setOption(newValue)
},
onClick(event, ownerInstance) {
// 调用 service 层的方法
ownerInstance.callMethod('onViewClick', {
test: 'test'
})
}
}
}
当我们需要对echarts的x轴或者y轴文本内容进行自定义时,需要使用到formatter属性
- 定义一个回调函数来对data的值进行修改
- 就是下面官方操作手册里说的这个
但是问题来了,当我使用formatter属性的时候,表格y轴上的文字完全没有变化,但是h5的页面上却有变化
- 这是为啥
- 因为uniapp的echarts使用的是renderjs,所以我们需要在renderjs里的setOption之前打印一下Option.
- 接着文章最上面的代码,加一行打印option
- 因为我的数据是从后台获取的,因此也可以在获取新数据的阶段打印option
updateEcharts(newValue, oldValue, ownerInstance, instance) {
// 监听 service 层数据变更
//这里的newValue就是新的option,也可以在初始化阶段打印option,只要setOption打印都一样的
console.log(newValue)
myChart.setOption(newValue)
}
首先说一下我的formatter是加在yAxis.axisLabel下的
震惊,yAxis.axisLabel里居然没有formatter! ! !
既然options里面没有formatter,那么手动添加一下就可以了!
//yAxis.axisLabe添加一个formatter属性,属性值是名为formatter的函数
newValue.yAxis.axisLabel.formatter = function formatter(v){
return '...'
}
这时候可以看到
option的yAxis.axisLabel里面存在了formatter! ! !
效果
总结
既然option里面没有formatter,那就在setOption之前手动添加一个进去~