vue 动态获取div宽高有时候为0的情况

时间:2023-03-08 17:54:21
vue 动态获取div宽高有时候为0的情况

 项目背景:

  需要使用echarts进行图表展示。由于div宽高是不固定的,因此需要先获取父级的宽高再把值赋予到图表的div中。

  需要使用 this.$nextTick(() => {    });方法,在mounted中,保证DOM渲染完全后,在进行echarts初始化。

<!--wifi数据采集-->
<template>
<div class="wifiCollectCtrl">
<div id="wifiCollectID"></div>
</div>
</template> <script>
import echarts from 'echarts'; export default {
name: "wifiCollect",
props: {
className: {type: String, default: 'chart'},
id: {type: String, default: 'wifiCollectID'}, },
data() {
return {
chart: null,
seriesData: '',
xAxisTxt: '',
color: [
'#3D89FE', '#9bca62', '#2ec7c9', '#b6a2de', '#5ab1ef',
'#8d98b3', '#e5cf0d', '#97b552', '#95706d', '#dc69aa',
'#07a2a4', '#9a7fd1', '#588dd5', '#f5994e', '#c05050',
'#59678c', '#c9ab00', '#7eb00a', '#6f5553', '#c14089'
]
};
},
mounted() {
this.$nextTick(() => { //使用nextTick为了保证dom元素都已经渲染完毕
this.initChart();
});
},
beforeDestroy() {
if (!this.chart) {
return
}
this.chart.dispose();
this.chart = null;
},
created() { },
methods: {
initChart() {
$("#wifiCollectID").width($(".wifiCollectCtrl").width());
$("#wifiCollectID").height($(".wifiCollectCtrl").height());
this.chart = echarts.init(document.getElementById(this.id));
this.chart.setOption({
color: this.color,
title: {
text: '',
},
calculable: true,
grid: {
left: '50px',
right: '3%',
bottom: '20px',
top: '15px'
},
xAxis: [
{
type: 'category',
// data : this.xAxisTxt,
data: ['花园小区', '锦园小区', '云台小区', '教师宿舍区'],
splitLine: {show: false},//去除网格线
axisLine: {
lineStyle: {
color: '#3D89FE',
width: 1
}
},
axisLabel: {
show: true,
textStyle: {
color: '#fff'
}
}
}
],
yAxis: [
{
type: 'value',
splitLine: {//去除网格线
show: true,
lineStyle: {
color: ['#1F4781'],
width: 1,
}
},
axisLine: {
lineStyle: {
color: '#3D89FE',
width: 1
}
},
axisLabel: {
show: true,
textStyle: {
color: '#fff'
}
}
}
],
series: [
{
name: '所属小区',
type: 'bar',
barMaxWidth: '30',
// data:this.seriesData,
data: [20, 340, 40, 39]
} ]
})
}
} }
</script> <style scoped>
.wifiCollectCtrl {
color: #333;
padding: 5px;
width: 100%;
height: 100%;
position: relative;
}
</style>