1、安装插件
npm install --save lodash.debounce
2、封装组件pc .vue
<template>
<div v-bind:style="styleObject" class="scale-box">
<slot></slot>
</div>
</template>
<script>
import debounce from "lodash.debounce"
export default {
props: {
width: {
type: Number,
default: 1920,
},
height: {
type: Number,
default: 1080,
},
},
components: {},
data() {
return {
scale: this.getScale(),
}
},
computed: {
styleObject(){
let obj = {
transform: `scale(${this.scale}) translate(-50%, -50%)`,
WebkitTransform: `scale(${this.scale}) translate(-50%, -50%)`,
width: this.width + "px",
height: this.height + "px",
}
return obj
}
},
mounted() {
this.getScale()
window.addEventListener("resize", this.setScale)
},
methods: {
getScale() {
// 固定好16:9的宽高比,计算出最合适的缩放比,宽高比可根据需要自行更改
console.log(window.innerWidth,'window.innerWidth');
let ww = window.innerWidth / this.width
let wh = window.innerHeight / this.height
return ww < wh ? ww : wh
},
setScale: debounce(function () {
// 获取到缩放比,设置它
let scale = this.getScale()
this.scale = scale
console.log(this.scale, "---")
}, 500),
},
beforeDestroy() {
window.addEventListener("resize", this.setScale)
},
}
</script>
<style scoped lang="scss">
.scale-box {
transform-origin: 0 0;
position: absolute;
left: 50%;
top: 50%;
transition: 0.3s;
}
</style>
3、使用刚才封装的pc
<template>
<pc>
<div class="fixing">
<!-- 头部 -->
<qheader></qheader>
<el-main>
<router-view></router-view>
</el-main>
</div>
</pc>
</template>
<script>
import qheader from "@/components/head/index.vue"
// 引入
import pc from "@/components/pc.vue"
export default {
name:"mainIndex",
// 注册组件
components: {
qheader,
pc
},
data() {
return {
};
},
};
</script>
<style lang="scss">
@import "style.scss";
</style>