echarts 在 vue 随浏览器窗口改变响应

本文探讨如何在Vue项目中使用Echarts实现图表随着浏览器窗口大小变化而响应式布局,结合Element-UI框架,提供了一种解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码基于element-ui框架

<template>
  <el-row :gutter="40">
    <el-col :span="9">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <p>登记人员占比
            <span style="color:#728ffc;padding-left:10px;">(总人数{{countNum}})</span>
          </p>
        </div>
        <!-- 人员比例图表 -->
        <div style="width:100%;height:100%;" ref="_person_chart"></div>
      </el-card>
    </el-col>
    <el-col :span="15">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>今日报表</span>
        </div>
        <!-- 今日统计报表 -->
        <div style="width:100%;height:100%;" ref="_statistical_chart"></div>
      </el-card>
    </el-col>
  </el-row>
</template>
<script>
// 引入 echarts 主模块。
import * as echarts from 'echarts/lib/echarts'
// 引入折线图。
import 'echarts/lib/chart/pie'
import 'echarts/lib/chart/bar'
// 引入提示框组件、标题组件、工具箱组件。
import 'echarts/lib/component/title'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/legend'
import home from '@/api/home'
var clearId
export default {
  data() {
    return {
      countNum: 0,
      options_person: {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          x: 'right',
          bottom: 'center',
          itemWidth: 20,
          itemHeight: 20,
          data: ['教职工', '学生', '访客', '社会人员', '其他']
        },
        series: [
          {
            name: '人员占比',
            type: 'pie',
            radius: ['60%', '80%'],
            center: ["40%", "50%"],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false,
                position: 'center'
              },
              emphasis: {
                show: true,
                textStyle: {
                  fontSize: '22',
                  fontWeight: 'bold'
                }
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data: [
              { value: 0, name: '教职工', itemStyle: { color: '#728FFC' } },
              { value: 0, name: '学生', itemStyle: { color: '#FFB22D' } },
              { value: 0, name: '访客', itemStyle: { color: '#3EB934' } },
              { value: 0, name: '社会人员', itemStyle: { color: '#FF6EEC' } },
              { value: 0, name: '其他', itemStyle: { color: '#FF6E9B' } }
            ]
          }
        ]
      },
      options_statistical: {
        title: {
          text: '进出人数',
          textStyle: {
            color: '#000',
            fontWeight: '400',
            fontSize: 14
          }
        },
        tooltip: {
          //提示框组件
          trigger: 'axis',
          formatter: '{b}<br/>{a0}: {c0}<br/>',
          axisPointer: {
            type: 'shadow'
          },
          textStyle: {
            color: '#fff',
            fontStyle: 'normal',
            fontFamily: '微软雅黑',
            fontSize: 12
          }
        },
        grid: {
          left: 0,
          right: 0,
          bottom: 0,
          top: 50,
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: [],
            axisLabel: {
              //坐标轴刻度标签的相关设置。
              //        interval: 0,//设置为 1,表示『隔一个标签显示一个标签』
              //    margin:15,
              textStyle: {
                color: '#000',
                fontStyle: 'normal',
                fontFamily: '微软雅黑',
                fontSize: 12
              },
              rotate: 65
            },
            axisTick: {
              //坐标轴刻度相关设置。
              show: false
            },
            axisLine: {
              //坐标轴轴线相关设置
              lineStyle: {
                color: '#fff',
                opacity: 0.2
              }
            },
            splitLine: {
              //坐标轴在 grid 区域中的分隔线。
              show: false
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            splitNumber: 5,
            axisLabel: {
              textStyle: {
                color: '#000',
                fontStyle: 'normal',
                fontFamily: '微软雅黑',
                fontSize: 12
              }
            },
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: ['#DCDCDC'],
                opacity: 1
              }
            }
          }
        ],
        series: [
          {
            name: '总数量',
            type: 'bar',
            data: [],
            barWidth: 10,
            barGap: 0, //柱间距离
            label: {
              //图形上的文本标签
              normal: {
                show: true,
                position: 'top',
                textStyle: {
                  color: '#000',
                  fontStyle: 'normal',
                  fontFamily: '微软雅黑',
                  fontSize: 12
                }
              }
            },
            itemStyle: {
              normal: {
                show: true,
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: '#FF6EEC'
                  },
                  {
                    offset: 1,
                    color: '#728FFC'
                  }
                ]),
                barBorderRadius: 50,
                borderWidth: 0
              }
            }
          }
        ]
      },
      homeBar: '',
      homePie: ''
    }
  },
  mounted() {
    this.drawLines();
    // 重点,能够响应浏览器窗口改变的代码:原理主要是
    // 监听浏览器窗口变化,进而重新绘制图表
    window.addEventListener('resize', () => {
      this.homeBar.resize();  // 多个图表,第一个图表
      this.homePie.resize();  // 多个图表,第二个图表
    });
  },
  methods: {
    drawLines() {
      // 基于echarts,初始化 echarts 实例并绘制图表
      this.homePie = echarts.init(this.$refs._person_chart);
      this.homePie.setOption(this.options_person);
      this.homeBar = echarts.init(this.$refs._statistical_chart)
      this.homeBar.setOption(this.options_statistical)
    },
    init() {
      home.homeReportBySchool().then((res) => {
        res.map((item, index) => {
          this.options_statistical.xAxis[0].data[index] = item.name
          this.options_statistical.series[0].data[index] = item.count
        })
        this.drawLines()
      })
    },
    scaleByPerson() {
      this.countNum = 0;
      home.homeScaleByPerson().then((res) => {
        let new_res = res.filter((item) => { return item.name != '总数' })
        let count_array = res.filter((item) => { return item.name == '总数' })[0]
        this.options_person.legend.data = new_res.map((i) => { return i.name })
        new_res.map((item, index) => {
          this.options_person.series[0].data[index].name = item.name;
          this.options_person.series[0].data[index].value = item.count;
        })
        this.countNum = (count_array && count_array.count) ? count_array.count : 0;
        this.drawLines()
      })
    }
  },
  created() {
    this.init()
    this.scaleByPerson()
    clearId = setInterval(() => {
      this.init()
    }, 5000)
  },
  destroyed() {
    clearTimeout(clearId);
  }
}
</script>

<style lang="scss" scoped>
.el-card.is-always-shadow,
.el-card.is-hover-shadow:focus,
.el-card.is-hover-shadow:hover {
  box-shadow: 4px 0 25px rgba(114, 143, 252, .1);
}

.box-card {
  height: 370px;
}
</style>
Vue3中使用ECharts浏览器自适应放大缩小通常是通过结合ECharts的resize事件以及响应式组件的特点来实现的。首先,你需要在每个ECharts实例上添加`resize`事件监听,当窗口大小发生变化时,这个事件会被触发。然后,在事件处理函数中,你可以获取到新的视口大小,并据此调整图表的大小。 以下是基本步骤: 1. 安装ECharts及其Vue绑定库(如vue-echarts): ```bash npm install echarts @vue/echarts ``` 2. 在Vue组件中初始化ECharts实例并设置resize事件: ```html <template> <div ref="chartWrapper" :style="{ width: '100%', height: '400px' }"></div> </template> <script> import { ECharts, registerComponent } from '@vue/echarts'; registerComponent('echarts', ECharts); export default { components: { ECharts, }, mounted() { this.initChart(); }, methods: { initChart() { const chart = this.$echarts.init(this.$refs.chartWrapper); // ... 其他ECharts配置 chart.resize = () => { this.resizeChart(chart); }; // 添加其他必要的事件和配置... }, resizeChart(chart) { // 根据浏览器视口尺寸调整图表大小和比例等参数 let viewWidth = document.documentElement.clientWidth; // 这里可以做缩放计算,比如动态设定宽度百分比 chart.resize({ width: viewWidth * 0.8, // 示例:将宽度调整为视口的80% // 如果需要保持原始高度比例,可以用viewHeight = viewWidth * chartOption.original.aspectRatio height: chart.getHeight(), // 或者根据实际需求计算高度 }); }, }, }; </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值