从0到1搭建一款页面自适应组件(Vue.js)
组件将根据屏幕比例及当前浏览器窗口大小,自动进行缩放处理。
建议在组件内使用百分比搭配flex进行布局,以便于在不同的分辨率下得到较为一致的展示效果。
使用前请注意将body的margin设为0,否则会引起计算误差。
fullScreenContainer.vue
<template>
<div id="full-screen-container" :ref="ref">
<template v-if="ready">
<slot></slot>
</template>
</div>
</template>
<script>
import autoResize from './autoResize.js'
export default {
name: 'DvFullScreenContainer',
mixins: [autoResize],
data () {
return {
ref: 'full-screen-container',
allWidth: 0,
scale: 0,
datavRoot: '',
ready: false
}
},
methods: {
afterAutoResizeMixinInit () {
const { initConfig, setAppScale } = this
initConfig()
setAppScale()
this.ready = true
},
initConfig () {
const { dom } = this
const { width, height } = screen
this.allWidth = width
dom.style.width = `${width}px`
dom.style.height = `${height}px`
},
setAppScale () {
const { allWidth, dom } = this
const currentWidth = document.body.clientWidth
dom.style.transform = `scale(${currentWidth / allWidth})`
},
onResize () {
const { setAppScale } = this
setAppScale()
}
}
}
</script>
<style lang="scss">
#full-screen-container {
position: fixed;
top: 0px;
left: 0px;
更多内容请见原文,原文转载自:https://blog.csdn.net/weixin_44519496/article/details/118721118