echarts 柱状图 折线图切换组件 基于Vue2

644 阅读1分钟

image.png image.png

使用步骤
1 引入: import barlineCharts from "@/views/carbon/components/DataEcharts/barlineCharts.vue";
2 注册: components: { barlineCharts },
3 页面引用 : <barlineCharts ref="blCharts" />
4 调用方法将值传入组件:`this.$refs.blCharts.initPage(data);`
5 组件接受参数 1: ChartsWidth 图表宽度 (字符串类型)默认 100%; 2:ChartsHeight 图表高度 (字符串类型)默认 500px

调用组件代码

<template>
  <div>
    <barlineCharts ref="blCharts" />
  </div>
</template>

<script>
import barlineCharts from "@/views/carbon/components/DataEcharts/barlineCharts.vue";
export default {
  components: { barlineCharts },
  mounted() {
    this.initCharts();
  },
  methods: {
    initCharts() {
      let testData = {
        message: "SUCCESS",
        data: {
          xlist: [2001, 2002, 2003, 2004, 2005],
          dataList: [
            {        
              ylist: ["-", "666", "199", "213", "-"],
              name: "第一消费产业(hwh)"
            },
            {
              ylist: ["200", "-112", "12", "333", "45"],
              name: "第二消费产业(kWh)"
            },
            {
              ylist: ["110", "122", "-132", "112", "123"],
              name: "人均社会用电量(hwh)"
            }
          ]
        }
      };
      this.$refs.blCharts.initPage(testData.data); //调用组件内方法且传值
    }
  }
 
};
</script>

<style></style>

组件代码包含图片,如不需要可以看下面简洁版

<template>
  <!-- // 柱状图和折线图切换的图标组件 -->
  <div class="chartsbox ">
    <el-radio-group
      v-model="chartVal"
      size="mini"
      class="changeChart"
      @change="onChange"
    >
      <el-radio-button label="line"
        ><img class="iconImg" v-if="chartVal == 'line'" :src="lines"/><img
          v-else
          class="iconImg"
          :src="line"
      /></el-radio-button>
      <el-radio-button label="bar"
        ><img class="iconImg" v-if="chartVal == 'bar'" :src="bar"/><img
          v-else
          class="iconImg"
          :src="bars"
      /></el-radio-button>
    </el-radio-group>

    <div
      ref="barLineDom"
      :style="{ width: ChartsWidth, height: ChartsHeight + 'px' }"
    ></div>
  </div>
</template>

<script>
import echarts from "echarts";
export default {
  name: "barlineCharts",
  props: {
    // 组件宽度 100%
    ChartsWidth: {
      type: String,
      default: "100%"
    },
    // 组件高度 默认500
    ChartsHeight: {
      type: String,
      default: "350"
    }
  },
  data() {
    return {
      myChart: "",
      line: require("@/assets/images/zxt22.png"),
      bar: require("@/assets/images/zzt22.png"),
      lines: require("@/assets/images/zxt11.png"),
      bars: require("@/assets/images/zzt11.png"),
      chartVal: "bar",
      sysData: ""
    };
  },
  // beforeDestroy() {
  //   this.myChart && echarts.dispose(this.myChart);
  //   this.myChart = null;
  // },
  methods: {
    onChange(e) {
      this.initPage(this.sysData, this.chartVal);
    },
    // 初始化页面&处理数据
    initPage(sysData, type = "bar") {
      this.sysData = sysData;
      // console.log(data);
      console.log(sysData);
      let legendData = [];
      let seriesData = [];
      let color1 = ["#6F30FF", "#FF861B", "#2393FA"];
      let color2 = ["#AB4DFF", "#FAD52C", "#15F1FC"];
      const hexToRgba = (hex, opacity) => {
        let rgbaColor = "";
        let reg = /^#[\da-f]{6}$/i;
        if (reg.test(hex)) {
          rgbaColor = `rgba(${parseInt("0x" + hex.slice(1, 3))},${parseInt(
            "0x" + hex.slice(3, 5)
          )},${parseInt("0x" + hex.slice(5, 7))},${opacity})`;
        }
        return rgbaColor;
      };
      sysData.dataList.forEach((element, index) => {
        legendData.push(element.name);
        let seriesDataItem = {
          name: element.name,
          type: type,
          barWidth: 20,
          smooth: true, //折现平滑的曲线
          symbol: "none",
          data: element.ylist,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: color1[index % color1.length]
            },
            {
              offset: 1,
              color: color2[index % color2.length]
            }
          ]),
          areaStyle: {
            // 折现下是否填充
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: hexToRgba(color1[index % color1.length], 0.3)
                },
                {
                  offset: 1,
                  color: hexToRgba(color2[index % color2.length], 0.1)
                }
              ],
              global: false
            }
          }
        };
        seriesData.push(seriesDataItem);
        this.initCharts(legendData, sysData.xlist, seriesData);
      });
    },
    // 初始化echarts
    initCharts(legendData, xAxisData, seriesData) {
      // legendData 图例数据 xAxisData X轴数据  seriesData数据
      let chartsColorType = "dark"; //图表颜色类型默认暗色系
      //获取dom初始化echarts
      this.myChart = echarts.init(this.$refs.barLineDom, chartsColorType);
      let option = {
        color: ["#8640FF", "#FCA103", "#4CB2FC"],
        backgroundColor: "#1A2140",
        // 鼠标悬停
        tooltip: {
          trigger: "axis",
          //触发类型;轴触发,axis则鼠标hover到一条柱状图显示全部数据,item则鼠标hover到折线点显示相应数据
          xisPointer: {
            //坐标轴指示器,坐标轴触发有效,
            type: "line" //默认为line,line直线,cross十字准星,shadow阴影
          }
        },
        legend: {
          top: 10,
          data: legendData
        },

        grid: {
          left: "1%",
          right: "1%",
          bottom: "3%",
          containLabel: true
        },
        xAxis: {
          type: "category",
          data: xAxisData,
          axisTick: {
            //x轴刻度值配置
            show: true,
            alignWithLabel: true, //柱状图在刻度值上剧中显示
            lineStyle: {
              color: "#2F3961",
              width: 2
            }
          },
          axisLine: {
            //x轴线的颜色
            show: true,
            lineStyle: {
              color: "#2F3961"
            }
          },
          axisLabel: {
            //x轴文字颜色
            textStyle: {
              show: true,
              color: "#A9B0CE"
            }
          }
        },

        yAxis: {
          type: "value",
          splitLine: {
            show: false
          },
          axisLine: {
            //x轴线的颜色
            show: true,
            lineStyle: {
              color: "#2F3961"
            }
          },
          axisLabel: {
            // y轴文字颜色
            textStyle: {
              show: true,
              color: "#A9B0CE"
            }
          },
          axisTick: {
            //y轴刻度线的颜色
            show: true,
            alignWithLabel: true,
            lineStyle: {
              color: "#2F3961",
              width: 2
            }
          }
        },
        series: seriesData
      };

      this.myChart.setOption(option);
    }
  }
};
</script>

<style lang="scss" scoped>
.chartsbox {
  position: relative;
  .chartBox {
    width: 100%;
    height: 400px;
    padding-right: 55px;
  }
  .noData {
    line-height: 400px;
    text-align: center;
    color: #ccc;
    font-size: 16px;
  }
  .changeChart {
    position: absolute;
    right: 20px;
    top: 10px;
    z-index: 100;
  }
  .iconImg {
    width: 20px;
    height: 17px;
  }
}
</style>

简单版 去掉切换图片

<template>
  <!-- // 柱状图和折线图切换的图标组件 -->
  <div>
    <div
      ref="barLineDom"
      :style="{ width: ChartsWidth, height: ChartsHeight + 'px' }"
    ></div>
  </div>
</template>

<script>
import echarts from "echarts";
export default {
  name: "barlineCharts",
  props: {
    // 组件宽度 100%
    ChartsWidth: {
      type: String,
      default: "100%"
    },
    // 组件高度 默认350
    ChartsHeight: {
      type: String,
      default: "350"
    }
  },
  data() {
    return {
      myChart: "",
    };
  },

  methods: {
    // 初始化页面&处理数据
    initPage(sysData) {
  
     let legendData = [];
      let seriesData = [];
      let color1 = ["#6F30FF", "#FF861B", "#2393FA"];
      let color2 = ["#AB4DFF", "#FAD52C", "#15F1FC"];
      const hexToRgba = (hex, opacity) => {
        let rgbaColor = "";
        let reg = /^#[\da-f]{6}$/i;
        if (reg.test(hex)) {
          rgbaColor = `rgba(${parseInt("0x" + hex.slice(1, 3))},${parseInt(
            "0x" + hex.slice(3, 5)
          )},${parseInt("0x" + hex.slice(5, 7))},${opacity})`;
        }
        return rgbaColor;
      };
      sysData.dataList.forEach((element, index) => {
        legendData.push(element.name);
        let seriesDataItem = {
          name: element.name,
          type: 'bar',
          barWidth: 20,
          smooth: true, //折现平滑的曲线
          symbol: "none",
          data: element.ylist,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: color1[index % color1.length]
            },
            {
              offset: 1,
              color: color2[index % color2.length]
            }
          ]),
          areaStyle: {
            // 折现下是否填充
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: hexToRgba(color1[index % color1.length], 0.3)
                },
                {
                  offset: 1,
                  color: hexToRgba(color2[index % color2.length], 0.1)
                }
              ],
              global: false
            }
          }
        };
        seriesData.push(seriesDataItem);
        this.initCharts(legendData, sysData.xlist, seriesData);
      });
    },
    // 初始化echarts
    initCharts(legendData, xAxisData, seriesData) {
      // legendData 图例数据 xAxisData X轴数据  seriesData数据
      let chartsColorType = "dark"; //图表颜色类型默认暗色系
      //获取dom初始化echarts
      this.myChart = echarts.init(this.$refs.barLineDom, chartsColorType);
      let option = {
        color: ["#8640FF", "#FCA103", "#4CB2FC"],
        backgroundColor: "#1A2140",
        // 鼠标悬停
        tooltip: {
          trigger: "axis",
          //触发类型;轴触发,axis则鼠标hover到一条柱状图显示全部数据,item则鼠标hover到折线点显示相应数据
          xisPointer: {
            //坐标轴指示器,坐标轴触发有效,
            type: "line" //默认为line,line直线,cross十字准星,shadow阴影
          }
        },
        legend: {
          top: 10,
          data: legendData
        },

        grid: {
          left: "1%",
          right: "1%",
          bottom: "3%",
          containLabel: true
        },
        xAxis: {
          type: "category",
          data: xAxisData,
          axisTick: {
            //x轴刻度值配置
            show: true,
            alignWithLabel: true, //柱状图在刻度值上剧中显示
            lineStyle: {
              color: "#2F3961",
              width: 2
            }
          },
          axisLine: {
            //x轴线的颜色
            show: true,
            lineStyle: {
              color: "#2F3961"
            }
          },
          axisLabel: {
            //x轴文字颜色
            textStyle: {
              show: true,
              color: "#A9B0CE"
            }
          }
        },

        yAxis: {
          type: "value",
          splitLine: {
            show: false
          },
          axisLine: {
            //x轴线的颜色
            show: true,
            lineStyle: {
              color: "#2F3961"
            }
          },
          axisLabel: {
            // y轴文字颜色
            textStyle: {
              show: true,
              color: "#A9B0CE"
            }
          },
          axisTick: {
            //y轴刻度线的颜色
            show: true,
            alignWithLabel: true,
            lineStyle: {
              color: "#2F3961",
              width: 2
            }
          }
        },
        series: seriesData
      };

      this.myChart.setOption(option);
    }
  }
};
</script>

<style>

</style>