默认状况下,当扭转容器尺寸时(比方更改分辨率,浏览器页面缩放),图表原先是多大还是多大,不会依据容器尺寸的变动而扭转,然而咱们都心愿:生成的图表可能依据容器的大小,做出对应的变动,这如何实现呢?

官网给出的计划是监听window对象的resize()事件,做出对应的更改。

然而看了鑫神的这篇文章 《检测DOM尺寸变动JS API ResizeObserver简介》 ,文中蕴含以下一些观点:

  • window对象的resize()事件只能监测窗体尺寸的变动
  • 有时候窗体的尺寸没变,然而DOM元素尺寸变动了,那resize()事件是监测不到的。
  • 有时候窗体的尺寸变了,可DOM元素的尺寸没变,那用resize()事件做监测就有些节约了。
  • 因为上述这些弊病,咱们须要一个真正能监测DOM元素尺寸变动的工具,这就是ResizeObserver对象

这就提供了一个新的思路,感觉很高级,现实际如下。

<template>  <div id="myChart" /></template><script>import * as echarts from 'echarts'export default {  name: 'Charts',  data () {    return {      myChart: null,      timer: null    }  },  methods: {    // 监测容器尺寸扭转    observeResize () {      const or = new ResizeObserver(entries => {        clearTimeout(this.timer)        this.timer = setTimeout(() => {          this.myChart && this.myChart.resize()        }, 100)      })      or.observe(document.getElementById('myChart'))    },    showChart () {      this.myChart = echarts.init(document.getElementById('myChart'))      const options = {        title: {          text: 'ECharts 入门示例'        },        tooltip: {},        legend: {          data: ['销量']        },        xAxis: {          data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']        },        yAxis: {},        series: [          {            name: '销量',            type: 'bar',            data: [5, 20, 36, 10, 10, 20]          }        ]      }      this.myChart.setOption(options)    }  },  mounted () {    this.showChart()    this.observeResize()  }}</script><style>  #myChart {    height: 300px;    border: 1px solid blue;  }</style>