HorizontalBarChart.vue 2.62 KB
<template>
  <div class="horizontal-bar">
    <p class="title">{{ title }}</p>
    <div ref="horizontalBarChart" style="width: 100%; height: 20vh;"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import resize from './../mixin/resize'

export default {
  name: 'HorizontalBarChart',
  mixins: [resize],
  props: {
    title: {
      type: String,
      default: '',
    },
    data: {
      type: Array,
      default: () => [
        {name: '<20岁', value: 4},
        {name: '20–30岁', value: 10},
        {name: '30–40岁', value: 25},
        {name: '40–50岁', value: 30},
        {name: '50–60岁', value: 20},
        {name: '60–70岁', value: 10},
        {name: '≥70岁', value: 1},
      ],
    },
    colors: {
      type: Array,
      default: () => [],
    },
  },
  mounted() {
    this.initChart(this.$refs.horizontalBarChart);
    this.drawChart();
  },
  methods: {
    drawChart() {
      const chart = echarts.init(this.$refs.horizontalBarChart);

      const option = {
        tooltip: {
          // trigger: 'axis',
          // axisPointer: {
          //   type: 'shadow',
          // },
          show: false
        },
        grid: {
          top: '5%',
          left: '6%',
          right: '8%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: {
          type: 'value',
          axisTick: {show: false},
          splitLine: {show: false}, // 去掉背景的竖线
          axisLabel: { show: false }
        },
        yAxis: {
          type: 'category',
          data: this.data.map(item => item.name),
          axisTick: {show: false}, // 去掉y轴刻度
          axisLine: {show: false},
          axisLabel: {
            textStyle:{
              padding:[0,20,0,0]
            }
          }
        },
        series: [
          {
            // name: '年龄分布',
            type: 'bar',
            data: this.data.map(item => item.value),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(
                  0, 0, 1, 0, // 渐变方向从左到右
                  this.colors
              ),
              barBorderRadius: 4
            },
            label: {
              show: true,
              position: 'right',
              valueAnimation: true,
              formatter: (params) => `${params.value}%` // 在柱状图右边展示x轴的数据和名称
            }
          },
        ],
      };

      chart.setOption(option);
    },
  },
};
</script>

<style lang="scss" scoped>
.horizontal-bar {
  margin: 2vh 0;
  .title {
    color: #333333;
    font-size: 16px;
    font-weight: 600;
  }
}
</style>