【VUE】echarts,自适应+防抖

什么是echarts

中文官网
在Vue中使用echarts

使用步骤

引入echarts

npm  i echarts --save-dev

在main.js中引入并注册为全局变量或者也可以只在页面中引用

// main.js
import echarts from 'echarts'
Vue.prototype.$echarts=echarts

vue页面

切记一定要设置高宽,我这里用百分比

<div id="pie_chart" style="width:100%;height:95%;"></div>

方法体

methods: {
	initChart() {	
		//这句申明建议写到外面去
		this.chart = this.$echarts.init(document.getElementById("pie_chart"), "macarons" )
		this.chart.setOption({
	        title: {
	          text: "51",
	          x: "center",
	          y: "center",
	          textStyle: {
	            fontWeight: "bolder",
	            align: "center",
	            fontSize: 18
	          }
	        },
	        tooltip: {
	          trigger: "item",
	          formatter: "{a} <br/>{b}: {c} ({d}%)"
	        },
	
	        series: [
	          {
	            color: ["green", "yellow", "red", "#bbb"],
	            animationDuration: 4000,
	            name: "运行状况",
	            type: "pie",
	            radius: ["50%", "60%"],
	            avoidLabelOverlap: false,
	            label: {
	              normal: {
	                show: false,
	                position: "left"
	              }
	            },
	            labelLine: {
	              normal: {
	                show: false
	              }
	            },
	            data: [
	              { value: 6, name: "正常" },
	              { value: 0, name: "保护" },
	              { value: 1, name: "故障" },
	              { value: 44, name: "脱机" }
	            ]
	          }
	        ]
      	});
		
	}
}

一定要在mounted调用 才能自适应 关闭页面后还要销毁监听

  mounted() {
    //检测 图标自适应
    this.initChart();
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize();
      }
    }, 100);
    window.addEventListener("resize", this.__resizeHandler);
  },
    beforeDestroy() {
    //销毁检测
    if (!this.chart) {
      return;
    }
    window.removeEventListener("resize", this.__resizeHandler);
    this.chart.dispose();
    this.chart = null;
  }

防抖

debounce方法(防抖术) 可以放到 公共工具包里 即utils 下面

export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

解释一下什么是防抖和节流

JS防抖函数debounce,underscore的防抖代码分析

JavaScript 函数防抖(debounce)的实现

JavaScript专题之跟着underscore学防抖

JavaScript专题之跟着underscore学节流

### Vue2 中 ECharts 实现自适应窗口大小 在 Vue2 项目中实现 ECharts 图表随着浏览器窗口大小的变化而自动调整,可以通过监听 `window` 的 `resize` 事件来触发 ECharts 的 `resize()` 方法。以下是具体实现方式: #### 使用 `mounted` 和 `beforeDestroy` 生命周期钩子管理事件监听器 为了确保组件卸载时移除不必要的事件监听器,在组件挂载完成后添加监听器,并在组件销毁前将其删除。 ```javascript export default { data() { return { chart: null, }; }, mounted() { this.initChart(); window.addEventListener('resize', this.handleResize); }, beforeDestroy() { if (this.chart) { window.removeEventListener('resize', this.handleResize); this.chart.dispose(); } }, methods: { initChart() { const chartDom = document.getElementById('main'); this.chart = echarts.init(chartDom); this.chart.setOption({ title: { text: 'ECharts Example' }, tooltip: {}, xAxis: {data: ['A', 'B', 'C']}, yAxis: {}, series: [{ name: '销量', type: 'bar', data: [5, 20, 36], }] }); // 设置初始尺寸 this.chart.resize(); }, handleResize() { if (this.chart) { this.chart.resize(); } } } } ``` 上述代码展示了如何初始化图表并绑定 `resize` 事件处理函数[^1]。每当窗口尺寸发生改变时都会调用 `handleResize` 函数重新计算图表布局。 #### 利用防抖技术优化性能 频繁触发的 `resize` 事件可能会给页面带来较大的负担,因此建议引入节流或防抖机制减少不必要的渲染操作。可以借助第三方库如 `throttle-debounce` 来简化这一过程[^4]。 ```bash npm install throttle-debounce --save ``` 接着修改之前的 `handleResize` 方法如下所示: ```javascript import { debounce } from 'throttle-debounce'; methods: { ... handleResize: debounce(300, function () { if (this.chart) { this.chart.resize(); } }) } ``` 这样就实现了更高效的响应式设计模式下的 ECharts 渲染逻辑。 #### 配置项中的 auto-resize 属性 如果希望进一步简化开发流程,则可以直接利用 ECharts 提供的内置选项——`autoresize` 参数。只需将此参数设为 true 即可让图表根据其父级 DOM 元素的变化自动调整自身大小[^3]。 ```html <div id="chart-container" style="height:400px;width:100%;"> </div> <script> var myChart = echarts.init(document.getElementById('chart-container'), null, {renderer: 'canvas'}); myChart.setOption({...}); // 开启自动缩放功能 myChart.group = ''; myChart.getZr().configParameters.autoResize = true; </script> ``` 注意这里使用的是低版本 API 调用来开启全局级别的自动重绘行为。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值