下载current-device包,获取当前环境(web/移动)、状态(横屏/竖屏)
npm i current-device
以下是功能代码setSize.js文件
import { onBeforeMount, onBeforeUnmount, reactive } from 'vue'
import device from "current-device";
export const useAutoSize = () => {
const styles = reactive({
width: '100%',
height: '100%',
transform: 'rotate(0deg)',
'transform-origin': '',
fontSize: '16px',
})
onBeforeMount(() => {
autoReSize();
device.onChangeOrientation(autoReSize);
window.addEventListener("resize", autoReSize);
})
onBeforeUnmount(() => {
window.removeEventListener("resize", autoReSize);
})
function autoReSize() {
let designWidth = 1920, rem2px = 100, unit = 'vw'
if (device.mobile() && device.portrait()) {
styles.width = window.innerHeight + 'px'
styles.height = window.innerWidth + 'px'
styles.transform = 'rotate(90deg)'
styles['transform-origin'] = `${window.innerWidth / 2}px center`
unit = 'vh'
} else {
styles.width = '100%'
styles.height = '100%'
styles.transform = 'rotate(0deg)'
styles['transform-origin'] = ''
}
styles.fontSize = `${(100 / designWidth) * rem2px}${unit}`
}
return styles
}
最后在页面index.vue中使用
<template>
<div :style="styles" class="version-four-container">
// ...content
</div>
</template>
<script setup>
import { useAutoSize } from './setSize'
const styles = useAutoSize();
// ...content
</script>
<style lang="less" scoped>
// ...content
</style>