一份 Echarts 问题清单

2,892 阅读2分钟

最近在做一个数据看板的项目,项目涉及很多数据可视化图表的功能,我采用的是百度的 Echarts,这里记录一下项目使用过程中遇到的一些问题和解决方案

echarts 版本为4.6.0

1、将柱状图的点击事件范围扩大到阴影部分

this.myChart.on('click', (params) => {
    // 点击事件
})

通过上面的代码注册点击事件后发现,事件只在点击柱状图时生效,点击阴影部分并不会触发

image.png

这样就带来了一个问题,如果数据量比较小,会导致柱状图点击事件难以触发,体验比较差,所以需要让柱状图的阴影部分也能响应点击事件

  • 解决办法:getZr()
this.myChart.getZr().on('click', (params) => {
    const pointInPixel = [params.offsetX, params.offsetY]
    if (this.myChart.containPixel('grid', pointInPixel)) {
        // 获取当前点击的x轴索引
        const xIndex = this.myChart.convertFromPixel({ seriesIndex: 0 }, pointInPixel)[0]
    }
})

2、图表点击事件多次触发问题

该问题有上一问题衍生而来,当我从渠道切换到品牌的时候,发现上面注册的点击事件触发了两次,切换3次就触发3次,到这里大概就知道是由于多次注册事件而引发的问题了

  • 解决办法:注册事件之前先off掉
this.myChart.getZr().off('click')
this.myChart.getZr().on('click', (params) => {
    const pointInPixel = [params.offsetX, params.offsetY]
    if (this.myChart.containPixel('grid', pointInPixel)) {
        // 获取当前点击的x轴索引
        const xIndex = this.myChart.convertFromPixel({ seriesIndex: 0 }, pointInPixel)[0]
    }
})

3、饼图文本超出被隐藏问题

image.png

如图,文字“ODM产品”超出容器被截断

  • 解决:series里的label设置alignTo的对齐方式,仅当 position 值为 'outer' 时有效
const option = {
    // 省略其他代码
    series: [
        {
            label: {
                // 增加代码
                position: 'outer',
                alignTo: 'edge',
                margin: 10
            }
        }
    ]
}

image.png

4、dataZoom 显示固定数量

dataZoom: [{
    type: 'inside',
    realtime: true,
    start: 0,
    end: 50
}, {
    show: true,
    realtime: true,
    height: 18, // 这里可以设置dataZoom的尺寸
    bottom: 6
}]

image.png

dataZoom常见设置都是设置start和end来圈定窗口范围的百分比,设置0-50也就是50%的显示范围,坏就坏在这个百分比上,现在我的数据一共只有5条,所以这里显示了3条数据,看起来没什么异样

当数据一多的时候,例如有200条数据

image.png

这时候的界面。。。

产品经理已经提刀来问了,能不能默认显示5条数据?

  • 解决办法:startValue、endValue
dataZoom: [{
    type: 'inside',
    realtime: true,
    startValue: 0,
    endValue: 5-1 // 显示5个,需要-1
}, {
    show: true,
    realtime: true,
    height: 18, // 这里可以设置dataZoom的尺寸
    bottom: 6
}]

image.png

如果需要禁止滚动条缩放可以设置zoomLock为true

5、页面切换后回来,图表空白

切出去别的页面后改变窗口大小,这时会触发图表的resize事件,由于页面缓存,图表获取不到缓存页面的DOM,所以echarts没有重新渲染导致空白。知道了原因后我们可以这样解决:

activated() {
  window.dispatchEvent(new Event('resize'))
}

在 activated 重新触发触发 resize 即可。

6、未完待续...