无痛编写可视化大屏组件

117 阅读1分钟

食用说明: 把设计稿直接放入插槽即可使用,要求插槽中的内容与设计稿的宽高一比一编写 可以直接看gitee上的DEMO保证一看就懂 DEMO地址:gitee.com/bao92353766…

// BaseScreen组件
<template>
  <div id="shellBox" :style="{ height: shellBoxHeight }" ref="shellBoxRef">
    <div :style="{
      position: 'relative', width: width + 'px', height: height + 'px',
      transform: `scale(${scale.widthRatio},${scale.heightRatio})`
    }">
      <div style="width: 1026px;height: 130px;" @click="openFull" class="btn"></div>
      <slot>
        <!-- 插槽里面内容的宽高为设计稿的宽高 -->
      </slot>
    </div>
  </div>
</template>

<script>
import elementResizeDetectorMaker from 'element-resize-detector';
import { debounce } from 'lodash';
export default {
  data() {
    return {
      // 正常100%就行了,但是要嵌入管理系统,就在非全屏状态下减去面包屑的高度
      shellBoxHeight: 'calc(100% - 34px)',
      // 原始的缩放比例
      baseProportion: 0,
      // 保持比例所需的缩放倍数
      scale: {
        widthRatio: 1,
        heightRatio: 1
      },
    }
  },
  // 设计稿的宽高
  props: {
    width: {
      type: Number,
      default: 1920
    },
    height: {
      type: Number,
      default: 1080
    },
  },
  mounted() {
    // 需保持的比例
    this.baseProportion = parseFloat((this.width / this.height).toFixed(5))
    // 监听dom变化
    this.listener = elementResizeDetectorMaker().listenTo(document.getElementById("shellBox"), () => {
      this.resize()
    });
  },
  methods: {
    openFull() {
      this.$refs.shellBoxRef.requestFullscreen()
    },
    resize: debounce(function () {
      const currentRate = this.$refs.shellBoxRef.clientWidth / this.$refs.shellBoxRef.clientHeight
      if (currentRate > this.baseProportion) {
        this.scale.widthRatio = parseFloat(((this.$refs.shellBoxRef.clientHeight * this.baseProportion) / this.width).toFixed(5))
        this.scale.heightRatio = parseFloat((this.$refs.shellBoxRef.clientHeight / this.height).toFixed(5))
      }
      else {
        this.scale.heightRatio = parseFloat(((this.$refs.shellBoxRef.clientWidth / this.baseProportion) / this.height).toFixed(5))
        this.scale.widthRatio = parseFloat((this.$refs.shellBoxRef.clientWidth / this.width).toFixed(5))
      }
    }, 50),
  },
}
</script>

<style scoped lang="scss">
#shellBox {
  width: 100%;
  background-color: #000000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.btn {
  position: absolute;
  right: 50px;
  opacity: 1;
  top: 60px;
  z-index: 999;
}
</style>

使用方法 image.png