PC端可以用postcss-pxtorem插件, 将px单位转化为rem单位
配置过程:
1.安装postcss-pxtorem(这里指定了版本)
npm i postcss-pxtorem@5.1.1 -D
2.vue.config.js里面配置postcss-pxtorem
import postCssPxToRem from 'postcss-pxtorem'
css: {
loaderOptions: {
postcss: {
plugins: [
postCssPxToRem({
//自适应,px>rem转换
rootValue: 16, // 浏览器默认值字体大小为16
selectorBlackList: [],
propList: ['*'],//需要转换的属性,这里选择全部都进行转换
}),
]
}
},
}
3.创建rem.js文件
//rem等比适配配置文件
//基准大小
const baseSize = 16
//设置 rem 函数
function setRem () {
//当前页面宽度相对于1920宽的缩放比例, 可根据自己需要修改
const scale = document.documentElement.clientWidth / 1920
//设置页面根节点字体大小, 字体大小最小为12
let fontSize = (baseSize * Math.min(scale, 2))>12 ? (baseSize * Math.min(scale, 2)): 12
document.documentElement.style.fontSize = fontSize + 'px'
}
//初始化
setRem()
//改变窗口大小重新设置rem, 这里最好加上节流
window.onresize = function () {
setRem()
}
4.在main.js引入
import '@/util/rem'
5.如果项目部署在线上后不生效,我的办法是在根目录创建postcss.config.js,将第二步vue.config.js里面的配置放在postcss.config.js中
module.exports = {
plugins: {
'postcss-pxtorem': {
rootValue : 16,
selectorBlackList : [],
propList : ['*'],
},
},
};
6.重启+执行
移动端需要两个插件postcss-pxtorem 和 amfe-flexible(用于设置rem基准值)
配置过程:
1.安装插件 amfe-flexible 是配置可伸缩布局方案,主要是将 1rem 设为 viewWidth/10
npm i postcss-pxtorem@5.1.1 -D
npm i amfe-flexible -D
2.在main.js中引入
import 'amfe-flexible'
3.然后就是postcss-pxtorem 配置步骤
配置postcss-pxtorem,可在vue.config.js、.postcssrc.js、postcss.config.js其中之一配置,权重从左到右降低,没有则新建文件,只需要设置其中一个即可:
为了方便 我是在 vue.config.js 配置的代码配置如下:
module.exports = {
//...其他配置
css: {
loaderOptions: {
postcss: {
plugins: [
require('postcss-pxtorem')({
rootValue: 37.5,
propList: ['*']
})
]
}
}
},
}
在.postcssrc.js或postcss.config.js中配置如下:
module.exports = {
"plugins": {
'postcss-pxtorem': {
rootValue: 37.5,
propList: ['*']
}
}
}
注意点:
1、rootValue根据设计稿宽度除以10进行设置,这边假设设计稿为375,即rootValue设为37.5;
2、propList是设置需要转换的属性,这边*为所有都进行转换。
通过以上配置我们就可以在项目使用了