需求描述:legend中点击图例默认行为是不显示该图例,而这不符合实际产品需求。我们需要的效果是:
    1、第一次点击时,只展示点击图例
    2、后续点击时、若图例状态为显示/隐藏,则修改状态为隐藏/显示
    3、当没有图例显示时,设置为全选状态
    4、全选状态下,重置为第一次点击
    全选控件我通过一个变量来判断是否展示,是因为系列少的时候控制不展示全选按钮

    1. // 显示全选功能
    2. legend: {
    3. width: '78%%',
    4. type: 'scroll',
    5. selector: this.hasSelector ? ['all'] : false
    6. },
    7. // 监听legendselectchanged、legendselectall事件
    8. setLegendEvents(firstSelect) {
    9. this.myChart.on('legendselectchanged', function(obj) {
    10. const { selected, name } = obj
    11. this.selected = selected
    12. let noSelected = 0
    13. const length = Object.keys(this.selected).length
    14. if (this.selected) {
    15. Object.keys(this.selected).forEach(key => {
    16. if (firstSelect) {
    17. this.selected[key] = false
    18. }
    19. if (key === name && firstSelect) { this.selected[key] = true }
    20. if (this.selected[key] === false) noSelected++
    21. })
    22. if (noSelected === 0) firstSelect = true
    23. else if (noSelected === length) {
    24. Object.keys(this.selected).forEach(key => {
    25. firstSelect = true
    26. this.selected[key] = true
    27. })
    28. } else {
    29. firstSelect = false
    30. }
    31. }
    32. this.setOption({
    33. legend: {
    34. selected: this.selected
    35. }
    36. })
    37. })
    38. this.myChart.on('legendselectall', function(obj) {
    39. firstSelect = true
    40. })
    41. }