记录:echarts柱状图点击选中变色

530 阅读1分钟

1. 效果

点击之前

image.png

点击之后

image.png

2. 运行环境

运行环境:vue2 + echarts@5.3.3

3.思路

echarts自身提供点击事件,并且可以拿到点击的相关参数,定义一个变量 indexLabel 用于对比

        // 数据
        data() {
            return {
               indexLabel: null 
            }
        }
        // 添加点击事件
        this.myChart.on('click',(param) => {
            this.indexLabel = param.name; 
            this.myChart.setOption(this.option)

        })

点击之后需要重新调用 *this.myChart.setOption(this.option)*才会重新渲染生效

4.具体实现

  1. x轴文字变色
        // 配置项
        this.option = {
            xAxis: {
                textStyle: {
                    color: this.handleColor
                }
            }
            ...
        }
        // 方法
        methods: {
            handleColor(str) {
                return this.indexLabel == str ? '#F6A131' :  '#67E6F8';
            }
        }
  1. 柱体变色
        // 配置项
        this.option = {
             series: [
                 {
                     itemStyle: {
                         normal: {
                            barBorderRadius: [6,6,0,0],
                            offset:0,
                            color: this.handleGradientColor
                        }
                     }
                     ...
                 }
             ]
             ...
        }
        // 方法
        methods: { 
            handleGradientColor(str) {
                return this.indexLabel == str.name ? 
                    // 这里我试过两个都是渐变色,效果不对
                    this.$echarts.graphic.LinearGradient(
                        0, 0, 0, 1,
                        [
                            {offset: 0, color: '#F6A131'},
                            {offset: 1, color: '#A15C00'}
                        ]
                    )
                    :  
                    '#67E6F8'
            }
        }

5.问题

        color: function(str) {
            // 直接写在配置项中,注意this的问题
        }

柱体从一个渐变色变成另一个渐变色暂时未实现,handleGradientColor 中三元表达式只能实现一个渐变色!欢迎大佬指点!