ResizeObserve 在 Echarts 的使用

2 篇文章 0 订阅

前言

前端图表经常要进行 resize 操作,一般我们会想到监听 window resize event, 但是这个事件只能监听 window 窗口大小的改变, 没有办法监听到某个div大小的改变

目前解决方案

ResizeObserver

下面是使用的例子

const resizeObserver = new ResizeObserver((enties, observer)=> {
   // 这里可以拿到观察的所有实体
});
const elem = document.querySelect('a');
// 观察 elem 这个元素
resizeObserver.observer(elem);

ResizeObserver 有兼容问题,但是我们可以用 resize-observer-polyfill

npm install resize-observer-polyfill --save
yarn add resize-observer-polyfill --save

下面看一个完整的例子 echart.vue

<template>
  <div class="chart-container" ref="chart"></div>
</template>

<script>
import Vue from 'vue';
import ResizeObserver from 'resize-observer-polyfill';
import throttle from 'lodash/throttle';

const echarts = require('echarts');
Vue.prototype.$echarts = echarts;

let resizeObserver = null;

export default {
  name: 'VEchart',
  props: {
    theme: String,
    options: {
      type: Object,
      default() {
        return null;
      },
      isLoading: {
        type: Boolean,
        default: false,
      },
    },
  },
  data() {
    return {
      instance: null,
    };
  },
  watch: {
    options(val) {
      if (val) {
        this.refresh(val);
      }
    },
    isLoading(val) {
      this.initChart();
      if (val) {
        this.instance.showLoading();
      } else {
        this.instance.hideLoading();
      }
    },
  },
  methods: {
    // init chart
    initChart() {
      this.instance = this.instance || this.$echarts.init(this.$refs.chart);
    },
    // 获取chart 实例
    getInstance() {
      this.initChart();
      return this.instance;
    },
    // 获取现有的 options
    getOption() {
      return this.getInstance.getOption();
    },
    // 刷新chart
    refresh(options, notMerge = false) {
      this.initChart();
      this.instance.setOption(options || this.options, notMerge);
    },
    // bind resize
    bindResize() {
      const deboundResize = throttle(() => {
        this.instance && this.instance.resize();
      }, 250);

      resizeObserver = new ResizeObserver((entries, observer) => {
        deboundResize();
      });

      resizeObserver.observe(this.$refs.chart);
    },
    // 解绑 resize
    unbindResize() {
      resizeObserver.unobserve(this.$refs.chart);
    },
  },
  mounted() {
    this.bindResize();
  },
  beforeDestroy() {
    // 销毁组件时,解绑 reszie
    this.unbindResize();
  },
};
</script>

<style scoped></style>

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

丢丢的大神

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值