1、根节点rem适配
1.1、body需要设置一个默认的字体大小,可以设置为16px
<style>
body{
font-size:16px;
height:100vh;
}
#app {
max-width: 750px;
min-width:320px;
overflow: hidden;
min-height: 100vh;
margin: 0 auto;
}
</style>
1.2、动态设置根节点rem
<template>
<!-- <router-view /> -->
<login></login>
</template>
<script>
import login from './page/login/index.vue'
export default {
components:{login},
name: "App",
data() {
return {
}
},
setup() {
const setRem = () => {
const pWidth = 750;
const pre = 100;
const windowWidth = document.documentElement.clientWidth;
document.documentElement.style.fontSize = (windowWidth / pWidth) * pre + 'px';
console.log('rem适配:',windowWidth,(windowWidth / pWidth) * pre + 'px');
}
return {
setRem
}
},
mounted() {
this.setRem();
window.addEventListener("resize", this.setRem, false);
},
//卸载之前
beforeUnmount() {
window.removeEventListener("resize", this.setRem, false)
},
};
</script>
说明:
设计稿是750px;
基点是100,即配置好后1rem=设计稿100px;
font-size: 30px=0.3rem;
2、插件适配
2.1、安装2个插件
cnpm/ npm / yarn install postcss-pxtorem@5.1.1 --save-dev
需要指定版本,不然可能会出错!!!cnpm/ npm / yarn install lib-flexible --save
2.2、 项目根节点添加文件:postcss.config.js
module.exports = {
plugins: {
'postcss-pxtorem': {
rootValue: 52,
// 根字体大小是 37.5
propList: ['*'],
selectorBlackList: ['.no__rem']
// 过滤掉.no__rem-开头的class,不进行rem转换处理
}
}
}
2.3、在工具类文件中新建rem.js文件(我放在public文件夹下)
// 设置基础根文件大小
let baseSize = 52
// rem 函数
function setRem () {
// 设计稿一般都是以375的宽度
const scale = document.documentElement.clientWidth / 750
// 设置页面根节点字体大小(“Math.min(scale, 2)” 指最高放大比例为2,可根据实际业务需求调整)
document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) + 'px';
console.log('px转rem:', baseSize * Math.min(scale, 2) + 'px')
}
// 调用方法
setRem()
// 监听窗口在变化时重新设置跟文件大小
window.onresize = function () {
setRem()
}
2.4、main.js文件里面引入rem.js
import '../public/rem.js'
说明:
配置好后重启服务器
设计稿750px;
配置好后代码750px=设计稿的750px