uniapp自动适配,在移动端正常显示,在宽屏设备上变为平行视界效果,在App.vue设置meta标签,使用Flexible方案进行移动端适配,请写出示例代码
时间: 2023-09-04 21:14:58 浏览: 55
在App.vue中添加以下代码:
```html
<template>
<div id="app">
<router-view/>
</div>
</template>
<script>
export default {
name: 'App',
created() {
// 自适应屏幕宽度
this.setRemUnit()
window.addEventListener('resize', this.setRemUnit)
},
destroyed() {
window.removeEventListener('resize', this.setRemUnit)
},
methods: {
setRemUnit() {
const clientWidth = document.documentElement.clientWidth
const scale = 375 / 10
document.documentElement.style.fontSize = (clientWidth / scale) + 'px'
}
}
}
</script>
<style lang="scss">
// 定义基准字号
$baseFontSize: 32px;
// 计算rem单位
@function px2rem($px) {
@return $px / $baseFontSize + rem;
}
// 定义样式
body {
font-size: $baseFontSize;
}
</style>
```
在上面的代码中,我们定义了一个 `setRemUnit` 方法,该方法会根据屏幕宽度计算出合适的 `font-size` 值,并将其设置到 html 标签上,从而实现自适应。同时,我们在样式中定义了一个基准字号 `$baseFontSize`,并提供了一个 `px2rem` 函数,用于将像素值转换成 rem 单位。
需要注意的是,我们使用了 Flexible 方案进行移动端适配,而不是直接设置 viewport。这是因为如果直接设置 viewport,虽然可以实现自适应,但是在宽屏设备上会出现拉伸变形的问题,而 Flexible 方案可以避免这个问题。