一、安装postcss-pxtorem和amfe-flexible
1.amfe-flexible
amfe-flexible是配置可伸缩布局方案,主要是将1rem设为viewWidth/10。
- yarn:yarn add postcss-pxtorem
- npm:npm i postcss-pxtorem -D
2.postcss-pxtorem
postcss-pxtorem是postcss的插件,用于将像素单元生成rem单位。
- yarn:yarn add amfe-flexible
- npm:npm i amfe-flexiblem -D
二、配置
配置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,// 根字体大小,如果设计图是750的话 记得除2
propList: ['*']
}
}
}
vue-cli3.0使用rem适配移动端,还需在src下新建utils文件夹,添加rem.js,在main.js中引入import './utils/rem'
// 基准大小(可随意指定,影响rem的数值)
const baseSize = 75
// 设置 rem 函数
function setRem() {
// 当前页面宽度相对于 750 宽的缩放比例,可根据自己需要修改。
const scale = document.documentElement.clientWidth / 750
// 设置页面根节点字体大小
document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) + 'px'
}
// 初始化
setRem()
// 改变窗口大小时重新设置 rem
window.onresize = function() {
setRem()
}