echarts使图表组件根据屏幕尺寸变更而重新渲染大小

效果图:

通过      window.addEventListener('resize', this.resizeChart); 实现

完整代码:

<template>
  <div class="dunBlock">
    <div class="char2" id="char2" ref="chart"></div>
  </div>
</template>

<script>
  import * as echarts from 'echarts';

  export default {
    props: ['chartData', 'colorArr'],
    data() {
      return {
        myChart: null,
      };
    },
    watch: {
      chartData: function() {
        this.initCC();
      }
    },
    mounted() {
      this.initCC();
      window.addEventListener('resize', this.resizeChart);
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.resizeChart);
    },
    methods: {
      initCC() {
        if (!this.chartData || !this.colorArr) return;

        const chartDom = this.$refs.chart;
        this.myChart = echarts.init(chartDom);

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#6a7985',
              },
            },
            formatter: function(params) {
              let result = `${params[0].axisValue}<br/>`;
              params.forEach(item => {
                result += `${item.marker}${item.seriesName}: ${item.value}<br/>`;
              });
              return result;
            },
          },
          legend: {
            data: ['折线数据', '柱状数据1', '柱状数据2'],
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '6%',
            containLabel: true,
          },
          dataZoom: [{
              type: 'inside', // 内置滚动
              xAxisIndex: 0,
              start: 0, // 初始滚动位置
              end: 50, // 显示的数据比例
            },
            {
              show: true, // 显示外部滚动条
              xAxisIndex: 0,
              height: 10, // 滚动条高度
              start: 0, // 初始滚动位置
              end: 50, // 显示的数据比例
              bottom: 0
            }
          ],
          xAxis: [{
            type: 'category',
            boundaryGap: true,
            data: this.chartData.labels,
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
              alignWithLabel: false,
            },
            axisLabel: {
              overflow: 'break', // 超出宽度换行,需要设置width
              interval: 1,
              margin: 7,
              fontSize: 11,
              rotate: 90, // 初始旋转角度
              formatter: function(value) {
                // 根据标签长度自适应旋转角度
                const labelLength = value.length;
                if (labelLength > 10) {
                  return `{rotate|${value}}`; // 长标签旋转显示
                } else {
                  return value; // 短标签正常显示
                }
              },
              rich: {
                rotate: {
                  rotate: 45,
                }
              },
            },
          }, ],
          yAxis: [{
            type: 'value',
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            splitLine: {
              show: false,
            },
          }, ],
          series: [{
              name: '折线数据',
              type: 'line',
              data: this.chartData.lineData,
              smooth: true,
              areaStyle: {
                color: this.colorArr[0] || 'rgba(150, 200, 250, 0.5)',
              },
              lineStyle: {
                color: this.colorArr[1] || '#5470C6',
              },
              symbol: 'circle',
              symbolSize: 10,
              itemStyle: {
                color: this.colorArr[1] || '#5470C6',
              },
              label: {
                show: true,
                position: 'top',
                formatter: '{c}',
              },
            },
            {
              name: '柱状数据1',
              type: 'bar',
              data: this.chartData.barData1,
              barGap: '-100%',
              barWidth: '40%',
              itemStyle: {
                color: this.colorArr[2] || 'rgba(60, 160, 180, 0.8)',
              },
              label: {
                show: true,
                position: 'insideTop',
                formatter: '{c}',
                color: '#fff',
              },
            },
            {
              name: '柱状数据2',
              type: 'bar',
              data: this.chartData.barData2,
              barWidth: '40%',
              itemStyle: {
                color: this.colorArr[3] || 'rgba(180, 60, 120, 0.8)',
              },
              label: {
                show: true,
                position: 'insideTop',
                formatter: '{c}',
                color: '#fff',
              },
            },
          ],
        };

        this.myChart.setOption(option);
      },
      resizeChart() {
        console.log('重新渲染图表');
        // 重新渲染图表
        this.myChart.resize();
      },
    },
  };
</script>

<style scoped>
  .dunBlock {
    width: 100%;
    height: 100%;
  }

  .char2 {
    width: 100%;
    height: 100%;
  }
</style>

引用示例:

<template>
  <div class="page">
    <div class="topBlock p_r">
      <div class="topTitle">
        整体运营
      </div>
      <div class="toptab" style="margin-left: 4rem;" @click="selectTop('1')"
        :class="topIdx==='1'?'tab-item-on':'tab-item-no'">
        employee
      </div>
      <div class="toptab" style="margin-left: 0.5rem;" @click="selectTop('2')"
        :class="topIdx==='2'?'tab-item-on':'tab-item-no'">
        hcp
      </div>
      <div class="toptab" style="margin-left: 2rem;" @click="selectTop('3')"
        :class="topIdx==='3'?'tab-item-on':'tab-item-no'">
        最近7天
      </div>
      <div class="toptab" style="margin-left: 0.5rem;" @click="selectTop('4')"
        :class="topIdx==='4'?'tab-item-on':'tab-item-no'">
        最新30天
      </div>
      <div class="" style="margin-left: 2rem;">
        <el-date-picker :default-value="$dayList" unlink-panels :picker-options="pickerOptions"
          style="height: 2.3rem;width: 260px;" v-model="timeParams" type="daterange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" @change="date_onChange">
        </el-date-picker>
      </div>

      <div class="topRight">
        当前选择日期范围:{{dayNow}}
      </div>
    </div>

    <div class="menuBlock p_r">
      <div class="menuItem" v-for="(item,idx) in menuList" :key="idx">
        <div class="menuTxt">
          {{item.txt}}
        </div>
        <div class="menuNum">
          {{item.mun}}
        </div>
      </div>
    </div>

    <div class="cards p_r">
      <div class="echartLineCard card">
        <echartLine v-if="echartLineDataShow" style="margin: 0 auto;" :colorArr="echartLineColorArr" :chartData="echartLineData"></echartLine>
      </div>
        <div class="echartLineCard card" style="margin-left: 1rem;">
          <echartLine v-if="echartLineDataShow" style="margin: 0 auto;" :colorArr="echartLineColorArr" :chartData="echartLineData"></echartLine>
        </div>
    </div>
  </div>
</template>

<script>

  import {
    getAllDatesInRange
  } from '@/utils/util'
  import echartLine from './components/echartLine'
  export default {
    components: {
      echartLine
    },
    data() {
      return {
        echartLineColorArr: ["#6358FE","#6358FE", "#1479FF", "#14A1F8"],
        echartLineData: {
          labels: getAllDatesInRange('2024-06-06','2024-08-12'),
          lineData: [220, 232, 191, 234, 290, 330, 310],
          barData1: [120, 132, 101, 134, 90, 230, 210],
          barData2: [150, 102, 101, 154, 190, 130, 110]
        },
        echartLineDataShow:false,
        menuList: [{
          txt: '总访问人数',
          mun: 60,
        }, {
          txt: '总访问量',
          mun: 1301,
        }, {
          txt: '工具',
          mun: 133,
        }, {
          txt: '首页',
          mun: 460,
        }, {
          txt: '自察',
          mun: 230,
        }, {
          txt: '疑诊',
          mun: 93,
        }, {
          txt: '筛查与诊断',
          mun: 34,
        }, {
          txt: '评估治疗',
          mun: 234,
        }, {
          txt: '随访',
          mun: 79,
        }, {
          txt: '多维护理',
          mun: 22,
        }],
        dayNow: '6/4/2024 - 8/8/2024',
        dataScreeningParams: {},
        topIdx: '',
        timeParams: ['', ''],
        pickerOptions: { //禁用今天之后的日期(包含今天)
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
        },
      }
    },
    watch: {},
    mounted() {
      let arr1=[];
      let arr2=[];
      let arr3=[];
      let arrDate = getAllDatesInRange('2024-06-06','2024-08-12');
      arrDate.forEach((item,idx)=>{
        arr1.push(idx+1 +5)
        arr2.push(idx+1 +10)
        arr3.push(idx+1 +20)
      })
      this.echartLineData.lineData = arr3;
      this.echartLineData.barData1 = arr2;
      this.echartLineData.barData2 = arr1;
      this.$forceUpdate()
      this.echartLineDataShow=true;
    },
    methods: {
      selectTop(idx) {
        this.topIdx = idx;
      },
      async date_onChange(val) {

        if (this.isRqusetSuo) return;
        this.isRqusetSuo = true;
        setTimeout(() => {
          this.isRqusetSuo = false;
        }, 200)
        console.log('选中日期', val);
        this.timeParams = [timestampToTime(new Date(val[0])), timestampToTime(new Date(val[1]))];
        this.tabItemIdx = '999';

        this.loadHide = message.loading('加载中..', 0);
        setTimeout(this.loadHide, 4000)
        this.dataScreeningParams.startTime = timestampToTime(new Date(val[0]))
        this.dataScreeningParams.endTime = timestampToTime(new Date(val[1]))
        this.dataScreeningParams.type = ''
        // await this.getDSCharts()
      },
    },
  
  }
</script>

<style lang="less">
  .cards{
    margin: 1rem;
    .echartLineCard{
      width: 49rem;
      height: 30rem;
    }
  }
  .card {
    border-radius: 0.5rem;
    background: #fff;
    padding: 1rem;
  }

  .menuBlock {
    margin-left: 0.5rem;
    width: 100%;
    .menuItem {
      margin-right: 0.4rem;
      width: 9.5rem;
      height: 6rem;
      border-radius: 0.4rem;
      background: rgb(213, 231, 255);
      text-align: center;

      .menuTxt {
        font-size: 1.2rem;
        color: #666;
        margin-top: 0.8rem;
      }

      .menuNum {
        margin-top: 0.1rem;
        font-size: 2rem;
        font-weight: bold;
      }
    }
  }

  .topBlock {
    padding: 1rem 0 1rem 1rem;

    .topRight {
      position: absolute;
      right: 2rem;
      margin-top: 0.6rem;
      font-size: 0.9rem;
      color: rgb(120, 132, 150);
      padding-left: 1rem;
      border-left: 2px solid rgb(114, 175, 255);
    }

    .topTitle {
      font-size: 1.6rem;
      font-weight: bold;
    }

    .toptab {
      border-radius: 0.3rem;
      width: 8rem;
      height: 2.3rem;
      justify-content: center;
      /*子元素水平居中*/
      align-items: center;
      /*子元素垂直居中*/
      display: -webkit-flex;
      cursor: pointer;
    }
  }

  .tab-item-no {
    color: rgb(91, 139, 201);
    border: 1px solid rgb(91, 139, 201);
    background: #fff;
  }

  .tab-item-on {
    background: rgba(91, 139, 201, 0.3);
    border: 1px solid rgb(91, 139, 201);
    color: rgb(91, 139, 201);
  }
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

a_靖

对你有帮助吗?打赏鼓励一下?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值