在项目中由于某些div元素在布局的时候需要初始化宽高,因为当浏览器缩小屏幕的时候需要重新刷新页面视图。
分析思路:
1、在store中创建state,用于保存当前浏览器的宽、高值。
2、在mounted中,使用window.onresize,监听页面大小是否发生变化。若发生变化则,则this.$store.commit修改store中的的宽、高;
3、在computed中获取到宽高的值。由于页面宽或者高其中一个变化都需要重新进行页面视图刷新,因此在computed中进行宽高合并,只需要监听合并后的值widthOrHight既可。
4、在watch中监听widthOrHight,若widthOrHight发生变化,则重新初始化div的宽高。
另外,由于子组件中图表初始化的宽高是父组件的宽高,在父组件中页面视图重新发生了变化,需要子组件重新渲染视图,因此只需要给子组件定义一个key值,然后修改key值则子组件会重新初始化。
<template>
<div>
<!--省略DOM代码-->
<videoDoorCtrl style="height: 90%;width: 100%;background-color: rgba(2, 31, 95, 0.3);" :key="compKey.videoDoorCtrl"></videoDoorCtrl><!--里面是echarts图表-->
<wifiCollect style="height: 90%;width: 100%;background-color: rgba(2, 31, 95, 0.3);" :key="compKey.wifiCollect"></wifiCollect><!--里面是echarts图表-->
</div>
</template> <script>
import { mapGetters } from 'vuex';
import videoDoorCtrl from './components/videoDoorCtrl'; // 视频门禁信息
import wifiCollect from './components/wifiCollect'; // wifi数据采集 export default {
name: "deviceQueryEle",
components:{
videoDoorCtrl,
wifiCollect
}, data() {
return {
compKey:{
videoDoorCtrl:3,
wifiCollect:6,
},
}
},
mounted() {
window.onresize = () => {
return (() => {
this.$store.commit('bodyWidthMut',document.body.clientWidth);
this.$store.commit('bodyHightMut',document.body.clientHeight);
})()
}
},
computed: {
...mapGetters(['bodyWidth','bodyHeight']),
widthOrHight(){ // 合并宽高,只需要监听一个值变化既可
return [this.bodyWidth,this.bodyHeight]
}
},
watch: {
widthOrHight(){ // 监听页面宽度或者高度
let that = this;
setTimeout(function () {
that.initPage(); // 监听到页面size发生变化,则重新初始化div的宽高
const index = 10;//随便定义一个随机数
that.compKey.videoDoorCtrl =that.compKey.videoDoorCtrl*1+index*1; // 需要刷新子组件的数据,只需要改变子组件的定义的key值
that.compKey.wifiCollect = that.compKey.wifiCollect*1+index*1; // 需要刷新子组件的数据,只需要改变子组件的定义的key值
}, 400)
}
},
computed: {},
beforeCreate() {},
created() {},
methods: {
mapFun(param){
// ……
},
initPage() {
let pageHig = $(window).height();
let pageWidth = $(window).width();
let pageHeaderHig = 60;
let pageMainHig = pageHig - pageHeaderHig; //得出地图部分的区域
$("#headerID").height(pageHeaderHig);
$("#mainID").height(pageMainHig);
$("#mapLeftID").height(pageMainHig - 80);
$("#mapLeftID").width(pageWidth * 0.23);
$("#mapRightID").height(pageMainHig - 80);
$("#mapRightID").width(pageWidth * 0.23);
mapFun(this.mapParam); // 初始化地图
},
}
}
</script> <style rel="stylesheet/scss" lang="scss" scoped> </style>