Vue 中监听窗口改变让echarts重绘

 
背景:绘制echarts图表后,窗口大小改变,图表布局未变,致使图表内容可能超出窗口。
解决办法:图表布局随窗口变化而变化。
 
具体实现:
1、组件初始化时,监听窗口改变,监听组件销毁时移除事件
mounted() {
    // 加载数据并绘制图表
    this.loadData();
    // 监听窗口尺寸改变
    window.addEventListener("resize", this.handleResizeChart); 
    // 监听组件销毁时移除事件
    this.$once("hook:beforeDestroy", () => {
      window.removeEventListener("resize", this.handleResizeChart);
    });
}

 

2、方法:绘制echarts图表、遍历重绘echarts图表
methods: {
    /**
     * 绘制echarts图表
     */
    drawChartWithOptions(id, options) {
      this.charts[id] = echarts.init(document.getElementById(id));
      this.charts[id].setOption(options);
    },
    /**
     * 遍历重绘echarts图表
     */
    handleResizeChart() {
      for (let key in this.charts) {
        if (this.charts[key] && this.charts[key].resize) {
          this.charts[key].resize();
        }
      }
    }
}

 

3、Vue hook 的使用
<!-- 外部组件监听组件内部声明周期 -->
<component @hook:update="handleComponentUpdate"/>

 

posted @ 2020-06-29 17:33  NovaKnight  阅读(1754)  评论(0)    收藏  举报