开发中常见场景

178 阅读1分钟

1.大屏适配到组件内

import SacleBox from '../components/sacleBox'

//sacleBox组件
<template>
  <div
    ref="ScaleBox"
    class="ScaleBox"
    :style="{
      width: width + 'px',
      height: height + 'px',
      transform:`${transform}`
    }"
  >
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: 'ScaleBox',
  props: {},
  data() {
    return {
      scale: 0,
      width: 1920,
      height: 1080,
      transform: 'scaleY(1) scaleX(1) translate(-50%, -50%)'
    }
  },
  mounted() {
    this.setScale()
    window.addEventListener('resize', this.debounce(this.setScale))
  },
  methods: {
    resize() {
      this.setScale()
    },
    getScale() {
      // 固定好16:9的宽高比,计算出最合适的缩放比
      const w = window.innerWidth / this.width
      const h = window.innerHeight / this.height
      return { x: w, y: h }
    },
    setScale() {
      // 获取到缩放比例,设置它
      const scale = this.getScale()
      this.transform = 'scaleY(' + scale.y + ') scaleX(' + scale.x + ') translate(-50%, -50%)'
    },
    debounce(fn, delay) {
      const delays = delay || 500
      let timer
      return function () {
        const th = this
        const args = arguments
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(function () {
          timer = null
          fn.apply(th, args)
        }, delays)
      }
    }
  }
}
</script>

<style lang="scss">
#ScaleBox {
  --scale: 1;
}
.ScaleBox {
  z-index: 100;
  transform-origin: 0 0;
  position: fixed;
  left: 50%;
  top: 50%;
  transition: 0.3s;
}
</style>

2. index 页面引用

//index.vue

<script>
import SacleBox from '../components/sacleBox'
import monitorView from '../components/view.vue'
import elementResizeDetectorMaker from 'element-resize-detector'
export default {
  name: '',
  components: { SacleBox, monitorView },
  data() {
    return {
      fullscreen: false
    }
  },
  computed: {},
  created() {
  },
  mounted() {
    const erd = elementResizeDetectorMaker()
    erd.listenTo(document.querySelector('.container'), (ele) => {
      this.$refs.sacleBox.resize()
    })
  },
  beforeDestroy() {},
  methods: {
    toggle() {
      this.fullscreen = !this.fullscreen
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  position: relative;
  height: 100%;
  // background: #020a2c url('../../../bigScreen/dict/cloud-bg.png') center/cover no-repeat;
  // background-size: 100% 100%;
}
.fullscreen-wrapper {
  width: 100%;
  height: 100%;
}
.full {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 34px;
  height: 34px;
  z-index: 1000;
  cursor: pointer;
  background: url('../../../bigScreen/dict/fullscreen.png') center/100% 100% no-repeat;
}
</style>