项目场景:
提示:
首页一般是由eacharts组合而成的。
问题描述
提示:
设置好echarts,但是当进行缩小屏幕时,却发现echarts并不能随着屏幕的尺寸而放大缩小
如图1所示
![](https://img-blog.csdnimg.cn/6ed5b88f1f944133bd3af7738da05937.png)
原因分析:
提示:没有给eachars添加自适应
因为在写echarts的时候给了宽度,并没有设置自适应宽度,所以会出现上图的情况
解决方案:
提示:
1、引用 "element-resize-detector" 监听 Dom 元素 宽度、高度 变化,
2、在父组件中设置ref进行绑定,在父组件的代码方法里进行监听 。
3、在父组件中的子组件上绑定widthAndheight这个属性,传递给子组件
4、子组件进行接收属性值
成功案例:
![](https://img-blog.csdnimg.cn/b6962a419791457fb1ead07a79ca2f09.png)
在父组件中设置ref进行绑定
在父组件中的方法里进行监听dom元素
<script>
methods: {
GetEqOutView() {
var elementResizeDetectorMaker = this.$detectors
// 创建实例,无参数
var erd = elementResizeDetectorMaker();
// 创建实例带参数
var erdUltraFast = elementResizeDetectorMaker({
strategy: "scroll",
callOnAdd: true,
debug: true
});
//监听id为test的元素 大小变化
erd.listenTo(this.$refs.IndexEcharts1Div, (element) => {
this.widthAndheight = {
width: element.offsetWidth + "px",
height: element.offsetHeight + "px",
}
this.widthAndheight1 = {
min_width: element.offsetWidth -90 + "px",
height: element.offsetHeight + "px",
}
// debugger
console.log('实时计算后的宽、高 :::', this.widthAndheight.width, '------', this.widthAndheight.height, '-----------------');
},
}
</script>
在子组件中接收使用
//Dom
<template>
<div ref="init" id="left_top" :style="{
'width': `${width}`,
'height': '100%'
}">
</div>
</template>
<script>
data() {
return {
m2R2Data: [],
width: '',
height: '',
main: '',
};
},
//父组件传过来的数据
props: {
seriesOpeion: [Array, Object],
baseOption: [Array, Object],
widthAndheight: [Array, Object]
},
//计算树形
computed: {
changeData() {
const { baseOption, seriesOpeion, widthAndheight } = this;
return { baseOption, seriesOpeion, widthAndheight };
},
},
//监听
watch: {
changeData(val) {
// debugger
this.width = val.widthAndheight.width //width宽度
this.height = val.widthAndheight.height //height高度
console.log('父级传递宽度', val.widthAndheight.width,val.widthAndheight.height)
this.main = this.$refs.init;
this.myChars = this.$echarts.init(this.main);
this.SetEchars(val.baseOption, val.seriesOpeion);
this.$nextTick(() => {
this.myChars.resize()
})
},
},
</script>