大屏开发全屏展示时,Echarts图表自适应

1,639 阅读2分钟

一、场景

在开发大屏时,时常要用到各种图表组件。在全屏展示下,要使这些图表自适应放大,本文介绍了一种较简便的方法。

二、效果展示

大屏.gif

三、思路

无论使用F11开启大屏,还是自己写一个按钮去触发,都可使用该套流程。因为他们都改变了页面的尺寸,所以我们的核心是resize方法。
通过resize方法,来改变一个状态字段(fullScreen),再通过监听fullScreen变化来触发echarts中的resize事件,以此达到自适应效果。

具体实现:

(1)在大屏主体vue文件中,加入resize事件
basicLayout中:(主体vue)
created() {
  // 加个nextTick,保证全屏展示,dom更新完成后,再触发事件 fullScreenChange
  window.onresize = () => {
    this.$nextTick(() => {
      this.$store.commit('fullScreenChange')
    })
  }
}

vuex中:
const state = {
  fullScreen: false
}
const mutations = {
  fullScreenChange(state) {
    state.fullScreen = !state.fullScreen
  }
}
const actions = {}
const getters = {}

export default {
  state,
  mutations,
  actions,
  getters
}

(2)每一个echarts的vue文件

一般是把图表文件都提出来做一个子组件,所以在写每一个图表组件的时候,都加上watch这套流程即可。
此处有一个小坑,图表dom的高度在获取时:
(1)若使用flex布局,暂时未遇到问题。
(2)在使用grid布局时,若某一个子项中,含2个图表时,可能会出现:点击全屏后,父元素高度 并未改变,即使我们设置的高度都是xx%,所以我们dom高度未变化,图表的resize方法也就没起作用。
(3)若出现高度未更新,我们可以手动将该图表dom的高度,换算成xx vh。用vh(视口单位)可以确保高度改变了,但由于vh是相对于视口的高度(1vh等于视口高度的1%)。
全屏模式下的视口与初始的视口并不一致,eg: 初始dom的height为7vh(70px),全屏dom的height为7vh(150px)。这样就会导致并不是成比例放大,放大后的高度会少一些像素,但我感觉肉眼看不出来,无伤大雅。

<template>
  <div class="echart_dom" ref="main"></div>
</template>

<script>
import echarts from 'echarts'
export default {
  props: ['circleBold'],
  computed: {
    fullScreen() {
      return this.$store.state.fullScreen
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    fullScreen: {
      handler() {
        this.chart && this.chart.resize()
      },
      deep: true
    },
    circleBold: {
      handler() {
        this.Draw_chart()
      },
      deep: true
    }
  },
  methods: {
    Draw_chart() {
      this.chart = echarts.init(this.$refs.main)
      let option = {} // 图表xxx
      // 有无数据
      let judge = this.circleBold.filter(item => {
        return item.value !== null
      })
      if (judge.length === 0) {
        option = {
          title: {
            text: '暂无数据',
            x: 'center',
            y: 'center',
            textStyle: {
              color: '#fff',
              fontWeight: 'normal',
              fontSize: 18
            }
          }
        }
      }
      this.chart.setOption(option, true)
    }
  }
}
</script>
<style lang="stylus" scoped>
.echart_dom
    height:666vh
</style>

四、尾言

有帮助的话,点个赞哈! 恭喜发财