在项目中由于某些 div 元素在布局的时候需要初始化宽高, 因为当浏览器缩小屏幕的时候需要重新刷新页面视图.
分析思路:
1, 在 store 中创建 state, 用于保存当前浏览器的宽, 高值.
2, 在 mounted 中, 使用 Windows.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'; // Wi-Fi 数据采集
- export default {
- name: "deviceQueryEle",
- components:{
- videoDoorCtrl,
- wifiCollect
- },
- data() {
- return {
- compKey:{
- videoDoorCtrl:3,
- wifiCollect:6,
- },
- }
- },
- mounted() {
- Windows.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 = $(Windows).height();
- let pageWidth = $(Windows).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>
来源: https://www.cnblogs.com/luoxuemei/p/10314221.html