封装一个大屏容器组件 发表于 2024-07-13 最近因为工作需要,封装了一个大屏容器组件。 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123<template> <div id="cg-container" ref="CgContainer"> <template> <slot></slot> </template> </div></template><script> import { debounce } from '@/utils/index.js' export default { name: 'CgContainer', props: { options: { type: Object, default: () => ({}), }, }, data() { return { width: 0, height: 0, originalWidth: 0, originalHeight: 0, ready: false, dom: null, observer: null, } }, methods: { // 初始化尺寸 initSize() { return new Promise((resolve) => { this.$nextTick(() => { if (this.options && this.options.width && this.options.height) { this.width = this.options.width this.height = this.options.height } else { this.width = this.$refs.CgContainer.clientWidth this.height = this.$refs.CgContainer.clientHeight } // 获取画布尺寸 if (!this.originalWidth || !this.originalHeight) { this.originalWidth = window.screen.width this.originalHeight = window.screen.height } resolve() }) }) }, updateSize() { if (this.width && this.height) { this.$refs.CgContainer.style.width = `${this.width}px` this.$refs.CgContainer.style.height = `${this.height}px` } else { this.$refs.CgContainer.style.width = `${this.originalWidth}px` this.$refs.CgContainer.style.height = `${this.originalHeight}px` } }, updateScale() { // 获取真实的视口尺寸 const currentWidth = document.body.clientWidth const currentHeight = document.body.clientHeight // 获取大屏最终的宽高 const realWidth = this.width || this.originalWidth const realHeight = this.height || this.originalHeight const widthScale = currentWidth / realWidth const heightScale = currentHeight / realHeight this.$refs.CgContainer && (this.$refs.CgContainer.style.transform = `scale(${widthScale}, ${heightScale})`) }, async onResize() { await this.initSize() this.updateScale() }, initMutationObserver() { const MutationObserver = window.MutationObserver this.observer = new MutationObserver(this.onResize) this.observer.observe(this.$refs.CgContainer, { attributes: true, attributeFilter: ['style'], attributeOldValue: true, }) }, removeMutationObserver() { if (this.observer) { this.observer.disconnect() this.observer.takeRecords() this.observer = null } }, }, mounted() { this.initSize() this.ready = false this.$nextTick(() => { this.initSize() this.updateSize() this.updateScale() window.addEventListener('resize', debounce(this.onResize, 100)) this.initMutationObserver() this.ready = true }) }, beforeDestroy() { window.removeEventListener('resize', this.onResize()) this.removeMutationObserver() }, }</script><style> #cg-container { position: fixed; top: 0px; left: 0; bottom: 0; right: 0; overflow: hidden; transform-origin: left top; z-index: 999; }</style>