Vue监听dom元素发生变化(用于echarts图表自适应屏幕)

1、下载依赖包

npm install element-resize-detector

2、在组件内引入依赖

var elementResizeDetectorMaker = require("element-resize-detector")

3、加载图表

<div id="warnstatistics"
           ref="typeEchart">
</div>
initEcharts(){
    
    
	option = {
    
    
    xAxis: {
    
    
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
    
    
        type: 'value'
    },
    series: [{
    
    
        data: [150, 230, 224, 218, 135, 147, 260],
        type: 'line'
    }]
	}
		// 若不为空,则释放图表实例
      if (this.myEchart  != null && this.myEchart != "" && this.myEchart != undefined) {
    
    
        this.myEchart.dispose()
      }
      this.myEchart = echarts.init(this.$refs.typeEchart)
      this.myEchart.setOption(option)
}

4、mounted中监听加载图表的dom元素

mounted(){
    
    
	this.resizeEchart ()
}
methods:{
    
    
	resizeEchart () {
    
    
      var erd = elementResizeDetectorMaker()
      erd.listenTo(document.getElementById("warnstatistics"), element => {
    
    
        // 重置图表
        this.myEchart? this.myEchart.resize() : ''
      })
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42164004/article/details/113937019