默认样式,点击柱子切换颜色
<div
style="width: auto; height: 300px; margin-top: 20px"
ref="echart"
></div>
<script>
import * as echarts from "echarts";
export default {
mounted() {
this.getEcharts();
},
methods: {
getEcharts() {
let myChart = echarts.init(this.$refs.echart);
let checkName = ""; //当前点击的柱状图横坐标名称
var option = {
tooltip: {//鼠标移入切换背景色
trigger: "axis",
showDelay: 0, // 显示延迟,添加显示延迟可以避免频繁切换,单位ms
axisPointer: {
type: "shadow",
shadowStyle: {
color: "rgba(255,171,96, 0.15)",
width: "1",
},
},
},
xAxis: {
type: "category",
data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
},
yAxis: {
type: "value",
},
series: [
{
data: [
120,
{
value: 200,//上边那个数也可以写成这样
},
150,
80,
70,
110,
{
value: 130,
itemStyle: {
color: "#FFAB60",//给最后一根柱子添加默认颜色,不想要可以直接删了
},
},
],
type: "bar",
//重点
itemStyle: {
color: function (params) {
if (checkName === params.name) {
return "#FFAB60"; //点击的柱子颜色发生改变
} else {
return "#E9EAEC"; //这里是柱子的默认颜色
}
},
emphasis: {
color: "#ffe3ca", //鼠标移入时改变柱子的颜色
},
},
},
],
};
myChart.setOption(option);
//柱子添加点击事件
myChart.on("click", function (params) {
checkName = params.name;
delete option
.series[0].data[option.series[0].data.length - 1].itemStyle; //点击删了默认最后一根柱子的颜色
myChart.setOption(option); //柱状图数据重组
});
},
}
}
</script>